Invalid token '=' in class struct interface in c# program [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
using System.Text;
using System.Threading.Tasks;
namespace Program
{
public class Book
{
public string title;
public string author;
public int pages;
Book.pages = 10;
}
}
I'm not sure why I'm getting the invalid token error. Please help.

You can use this code, if you want to set default value for pages.
public class Book
{
public string title { get; set; }
public string author { get; set; }
public int pages { get; set; } = 10;
}
But if you want to set value after create your class you can use this code:
first time you should create instance of your object and set value.
public class Book
{
public string title { get; set; }
public string author { get; set; }
public int pages { get; set; }
}
Book book = new Book { pages = 10 };
And you can also use constructor to set default value.
public class Book
{
public Book()
{
this.pages = 10;
}
public string title { get; set; }
public string author { get; set; }
public int pages { get; set; }
}

Related

ISSUE READING NESTED JSON OBJECT IN C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
I have an issue reading values (nationalId,surname,givenNames) from a nested json object below. Getting the error System.ArgumentNullException: Value cannot be null. (Parameter 'value')
Below is my Json string and Code respectively;
{
"return": {
"transactionStatus": {
"transactionStatus": "Ok",
"passwordDaysLeft": 35,
"executionCost": 0.0
},
"nationalId": "123456789",
"surname": "JOHN",
"givenNames": "DOE"}}
C# CODE, WHERE person_jObject Holds The JSON Above
JObject person_jObject = JObject.Parse(content5);
person.nationalId = person_jObject["nationalId"].Value<string>();
person.surname = person_jObject["surname"].Value<string>();
person.givenNames = person_jObject["givenNames"].Value<string>();
This should get you what you want:
// Usage:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
//
public class Return
{
public TransactionStatus transactionStatus { get; set; }
public string nationalId { get; set; }
public string surname { get; set; }
public string givenNames { get; set; }
}
public class Root
{
public Return #return { get; set; }
}
public class TransactionStatus
{
public string transactionStatus { get; set; }
public int passwordDaysLeft { get; set; }
public double executionCost { get; set; }
}
From https://json2csharp.com/
Of course, this won't help you if your Person object is broken.
you have a bug in your code, you need to use root "return" property
person.nationalId = person_jObject["return"]["nationalId"].Value<string>();
but you don't need to assign each property, if you need just person, just parse your json and deserialize a person part only
Person person=JObject.Parse(content5)["return"].ToObject<Person>();
assuming that your class person is like this
public class Person
{
public string nationalId { get; set; }
public string surname { get; set; }
public string givenNames { get; set; }
... could be another properties
}

"If is class" Condition Failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
Hi I have 3 base interfaces:
public interface IKlarfDefect
{
int TEST { get; set; }
int DEFECTID { get; set; }
}
public interface IKlarfDefect <TImageListInfo> : IKlarfDefect
{
List<TImageListInfo> KlarfImageList { get; set; }
}
public interface IHasKlarfImageList<TImageListInfo>
{
List<TImageListInfo> KlarfImageList { get; }
}
These classes implement it:
public class CIMKlarfDefect : IKlarfDefect, IHasKlarfImageList<CIMKlarfImageListInfo>
{
public int TEST { get; set; }
public int DEFECTID { get; set; }
public List<CIMKlarfImageListInfo> KlarfImageList { get; set; } = new List<CIMKlarfImageListInfo>();
}
public class RMTKlarfDefect : IKlarfDefect, IHasKlarfImageList<CIMKlarfImageListInfo>
{
public int TEST { get; set; }
public int DEFECTID { get; set; }
public List<RMTKlarfImageListInfo> KlarfImageList { get; set; } = new List<RMTKlarfImageListInfo>();
}
Then I have this function in another class that tries to read through these classes:
internal static string CreateCIMDefectListString(IEnumerable<IKlarfDefect<IKlarfImageListInfo>> klarfDefectList)
{
StringBuilder defectListString = new StringBuilder();
defectListString.AppendLine("");
foreach (var klarfDefect in klarfDefectList) {
defectListString.Append(klarfDefect.TEST).Append(" ");
defectListString.Append(klarfDefect.DEFECTID).Append(" ");
if (klarfDefect is IHasKlarfImageList<IKlarfImageListInfo> grcKlarfDefect)
{
if (grcKlarfDefect.KlarfImageList.Count == 0)
{
defectListString.Append("N;");
defectListString.AppendLine();
}
}
}
return defectListString.ToString();
}
It compiles but the if statement fails when I am passing in either RMTKlarfDefect or CIMKlarfDefect. Might anyone know why this is?
if klarfDefect is IHasKlarfImageList grcKlarfDefect
fails as in, it doesn't return true which would allow it to process the imagelist
Your if statement says
if (klarfDefect is IHasKlarfImageList<IKlarfImageListInfo> grcKlarfDefect)
But your classes implement
IHasKlarfImageList<CIMKlarfImageListInfo>
So you need to update your if statement accordingly:
if (klarfDefect is IHasKlarfImageList<CIMKlarfImageListInfo> grcKlarfDefect)

Calling properties of one class into another class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have two classes like below and I want to use InvoiceItem properties at Invoice class and add to AddInvoiceItem method but I receive error.
public class InvoiceItem
{
public int InvoiceItemId { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public double Cost { get; set; }
}
public class Invoice
{
public int InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public List<InvoiceItem> LineItems { get; set; }
public void AddInvoiceItem(InvoiceItem invoiceItem)
{
LineItems.Add(invoiceItem);
}
From the little you've shown, most likely you haven't actually created your list.
Try
public List<InvoiceItem> LineItems { get; set; } = new List<InvoiceItem>();

C# having Enums of Enums [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Assuming I have an enum category with some values:
enum Category {
ProgrammingBooks
CookingBooks
}
and I want each enum to have his own enum, for instance:
ProgrammingBooks will hold:
enum ProgrammingBooks {
CSharp,
Java,
Cpp
}
I saw a solution suggesting this:
enum Fauna {
enum Type { MAMMAL, BIRD }
TIGER(Type.MAMMAL),
LION(Type.MAMMAL),
PEACOCK(Type.BIRD),
OWL(Type.BIRD);
private final Type type;
Fauna(Type type) { this.type = type; }
}
with the usage:
Stream.of(Fauna.values()).filter(f -> f.type == BIRD).toList()
However, I'm just a beginner and I look for something that even if I do not know and should learn, wont go hardcore on me. I do not understand the example I mentioned (which I found on StackOverFlow).
Use classes or interfaces. For example:
public enum Category
{
ProgrammingBooks,
CookingBooks
}
public interface IBook
{
Category BookType { get; set; }
string Title { get; set; }
string Author { get; set; }
// ...
}
public class ProgrammingBook: IBook
{
public ProgrammingBook()
{
this.BookType = Category.ProgrammingBooks;
}
public string Author { get; set; }
public string Title { get; set; }
public Category BookType { get; set; }
// ...
}
public class CookBook : IBook
{
public CookBook()
{
this.BookType = Category.CookingBooks;
}
public string Author { get; set; }
public string Title { get; set; }
public Category BookType { get; set; }
// ...
}
If you want to support "sub-types" you could provide properties that only belong to a specific class and not into the interface because not every book is about programming. For example:
public enum ProgrammingLanguage
{
CSharp,
Java,
Cpp
}
public class ProgrammingBook: IBook
{
// a constructor that takes the ProgrammingLanguage as argument
public ProgrammingBook(ProgrammingLanguage language)
{
this.BookType = Category.ProgrammingBooks;
this.Language = language;
}
public ProgrammingLanguage Language { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public Category BookType { get; set; }
// ...
}
Why i use interfaces at all? Because all books have something in common(f.e. they all have a title and an author). So you can benefit from Polymorphism:
var library = new List<IBook>();
var book1 = new ProgrammingBook(ProgrammingLanguage.CSharp) {Title = "C# in Depth", Author = "Jon Skeet"};
var book2 = new CookBook() { Title = "Everyday Superfood", Author= "Jamie Oliver" };
library.Add(book1);
library.Add(book2);
// now you can loop all and you know that all books have these properties
foreach (IBook book in library)
{
Console.WriteLine("Title: {0} Type: {1}", book.Title, book.BookType.ToString());
}
or if you only want to get programming-books:
foreach (IBook book in library.Where(b => b.BookType == Category.ProgrammingBooks))
{
// ...
}
the same with LINQ's Enumerable.OfType method which just checks the type:
foreach (IBook book in library.OfType<ProgrammingBook>())
{
// ....
}
Enum is just a representation of an integer with text. It cannot hold sub categories or anything but an integer.
You should create a class for the categories and hold an enum of the sub categories in each of them.
public class ProgrammingBook
{
public BookType Type{get;set;}
}
enum BookType {
CSharp,
Java,
Cpp
}

Entity framework code first no errors but not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Why my codes is not working?
When I try to run the console application it's always stop on db.Blogs.Add(blog) and never continue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace CodeFirstNewDatabaseSample
{
class Program
{
static void Main(string[] args)
{
using(var db = new BloggingContext())
{
Console.Write("Enter the name of new Blog:");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog); //Stop working here but no error.
db.SaveChanges();
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.Write(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Post { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
public BloggingContext()
: base("Data Source=(localdb)\v11.0;Initial Catalog=CodeFirstNewDatabaseSample.BloggingContext;Integrated Security=True")
{
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
}
When I enter ASP.NET Blog and pressed enter there's nothing happen.
It should create a new database with 2 tables named Blog and Post
and show the message (All blogs in the database: ASP.NET Blog)
Sorry for bad English, Please help
Your code is clear and straightforward but you have to change the connection string to the following format
public class BloggingContext : DbContext
{
public BloggingContext()
: base(#"Data Source=(localdb)\v11.0;Initial Catalog=CodeFirstNewDatabaseSample.BloggingContext;Integrated Security=True")
{
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
you miss the "#" sign in the beginning of the connection string to avoid the escape characters.

Categories