Well I have a class like this and I want to store in a list which is defined as a static variable. I was following the reference here: Storing data into list with class
public class Faculty
{
public string Name { get; set; }
public string Dept { get; set; }
public string[] subInterest = new string[4];
}
However when I try to initialize the list as follows I have problem with the array part: Invalid initializer member declarator
SaveDirectory.list_of_faculty.Add(
new Faculty
{
Name = txtTeachherName.Text,
Dept = cmbDepts.Items.CurrentItem.ToString(),
subInterest[0] = "HELLO"
});
What am I doing wrong?
You can't reach in to your object and initialize members of an array that it holds using initializer syntax. You could work around this as follows:
var fac = new Faculty {
Name = txtTeachherName.Text,
Dept = cmbDepts.Items.CurrentItem.ToString(),
subInterest = new []{"HELLO", null, null, null}}
or after initialization:
fac.subInterest[0] = "HELLO";
The problem is due to:
subInterest[0] = "HELLO"
You can not partially initialize an array in Object Initializer, either it is full or nothing, You can do:
subInterest = new string[]{"HELLO"}
But, this will leave the array subInterest with size 1, not as size 4, as you have defined in your class. To get the array of same size you can do:
subInterest = new string[]{"HELLO",null,null,null}
Another option is to use List<string> instead of an Array. You can initialize it with value and later you can add items to it.
Modify your class like:
public class Faculty
{
public string Name { get; set; }
public string Dept { get; set; }
public List<string> subInterest;
}
and then:
new Faculty
{
Name = txtTeachherName.Text,
Dept = cmbDepts.Items.CurrentItem.ToString(),
subInterest = new List<string>(){"HELLO"}
};
Using a constructor can also solve the problem like
public class Faculty
{
public string Name { get; set; }
public string Dept { get; set; }
public string[] subInterest = new string[4];
public Faculty(string name, string dept, string[] si)
{
this.Name = name;
this.Dept = dept;
this.subInterest = si;
}
}
Then instantiate the faculty class
string[] subinterest = new string[]{"reading","swmming",null,null};
var fac = new Faculty("dgdfgdfgfg","dfgdgfgdfg", subinterest);
Related
I need to deserialize a JSON string into a type which is not know at compile time. There are several classes that it can be deserialized into. The name of the class is provided as input into the application and based on that I want to instantiate the class (already done this through reflection):
var type = Type.GetType(className);
var myClassInstance = (IParser)Activator.CreateInstance(type);
...and then use its type as the generic type parameter for JsonConvert.DeserializeObject<typeof(myClassInstance).Name>(jsonString) but that doesn't work.
How can I provide the class to DeserializeObject<>() dynamically?
Instead of using an generic method overload like JsonConvert.DeserializeObject<T>(String) and having to resort to reflection as some comments state, you could simply use the non generic counterpart JsonConvert.DeserializeObject(String, Type), which just takes in a Type instance like you already have!
Implementation
Initialization
var class1s = new Class1() {
ID = 1, Name = "Test", Comment = "This Code is Tested!."
};
var class2s = new Class2() {
xVal1 = 1, XVal2 = 5, xval3 = 10
};
var JSON1 = Newtonsoft.Json.JsonConvert.SerializeObject(class1s);
var JSON2 = Newtonsoft.Json.JsonConvert.SerializeObject(class2s);
Calling Functions
var classname1 = typeof(Class1).FullName;
var type1 = Type.GetType(classname1);
var classname2 = typeof(Class2).FullName;
var type2 = Type.GetType(classname2);
var c = LocalConverter(JSON1, type1);
var c2 = LocalConverter(JSON2, type2);
Class Models
public class Class1 {
public int ID {
get;
set;
}
public string Name {
get;
set;
}
public string Comment {
get;
set;
}
}
public class Class2 {
public int xVal1 {
get;
set;
}
public int XVal2 {
get;
set;
}
public int xval3 {
get;
set;
}
}
Required Method
private object LocalConverter(string o, Type xtype) {
return Newtonsoft.Json.JsonConvert.DeserializeObject(o, xtype);
}
I have a model like this that includes the OwnerProductRegistration and AttachmentList.
public class OwnerProductRegistration
{
public string CustomerFirstName { get; set; }
public string CustomerPhoneMobile { get; set; }
public List<AttachmentList> AttachmentLists { get; set; }
}
public class AttachmentList
{
public string FileName { get; set; }
public string Description { get; set; }
}
OwnerProductRegistration model = new OwnerProductRegistration();
AttachmentList attachmentList = new AttachmentList();
model.CustomerFirstName = "Test";
model.CustomerPhoneMobile = "1234567890";
attachmentList.FileName = "FileNameTest";
attachmentList.Description = "foo";
I want to send the entire 'OwnerProductRegistration' model with the AttachmentList data included. When I check the value contents of model, it shows the AttachmentList as null. How do I include the AttachmentList data with the model?
You must first instantiate the list on your model property, then add the attachment list to it. You can accomplish both like so:
model.CustomerFirstName = "Test";
model.CustomerPhoneMobile = "1234567890";
attachmentList.FileName = "FileNameTest";
attachmentList.Description = "foo";
model.AttachmentLists = new List<AttachmentList> { attachmentList };
If you don't want to use a collection initializer, you can break the operation up like this:
model.AttachmentLists = new List<AttachmentList>();
model.AttachmentLists.Add(attachmentList);
You're not setting the AttachmentLists property anywhere. Try this, it's similar to yours, but the property is set in the last line.
public class OwnerProductRegistration
{
public string CustomerFirstName { get; set; }
public string CustomerPhoneMobile { get; set; }
public List<AttachmentList> AttachmentLists { get; set; }
}
public class AttachmentList
{
public string FileName { get; set; }
public string Description { get; set; }
}
OwnerProductRegistration model = new OwnerProductRegistration();
AttachmentList attachmentList = new AttachmentList();
model.CustomerFirstName = "Test";
model.CustomerPhoneMobile = "1234567890";
attachmentList.FileName = "FileNameTest";
attachmentList.Description = "foo";
model.AttachmentLists = new List<AttachmentList> { attachmentList };
You can as well use Object Initializer and Collection initializer syntax available from C#3 like below
OwnerProductRegistration model = new OwnerProductRegistration
{
CustomerFirstName = "Test",
CustomerPhoneMobile = "1234567890",
AttachmentLists = new List<AttachmentList>
{
new AttachmentList
{
FileName = "FileNameTest",
Description = "foo",
}
}
}
right now, I use this command to initialize a list of objects and it works fine.
public class RelatedBlog
{
public string trekid { get; set; }
public string imagepath { get; set; }
public RelatedBlog(string trekid, string imagepath)
{
this.trekid = trekid;
this.imagepath = imagepath;
}
}
trek.relatedblog = new List<RelatedBlog>
{
new RelatedBlog("trekid", "../Images/image.jpg"),
};
However, lately I have decided that instead of single string as a first property, I want to have an array of several strings - with the size up to 4 (but it can be also fixed and I can enter nulls during initialization). This is the code I am using, but it doesnt work, it expects some more "(" when I call the constructor.
public class RelatedBlog
{
public string[] trekid { get; set; }
public string imagepath { get; set; }
public RelatedBlog(string[] trekid, string imagepath)
{
this.trekid = trekid;
this.imagepath = imagepath;
}
}
trek.relatedblog = new List<RelatedBlog>
{
new RelatedBlog({"string1", "string2"}, "../Images/image.jpg"),
};
Can someone advise me where I make a mistake and how to initialize this list properly. Thanks a lot
Use:
trek.relatedblog = new List<RelatedBlog>
{
new RelatedBlog(new[] {"string1", "string2"}, "../Images/image.jpg")
};
You are using implicitly typed array, the compiler can detect the type inside array but you have to inform it that you are passing an array:
var arr1 = new[] { "hello", "world" };
is equal to
var arr2 = new string [] { "hello", "world" };
I'm not using this in a real app but I was just curious on how to do this (C#).
I set one record of sample data in the constructor :
public class MikesClass
{
public MikesClass()
{
Id = 01; Name = "Mike";
}
public int Id { get; set; }
public string Name { get; set; }
}
but I'm confused on how to set another record in it :
public MikesClass()
{
Id = 01; Name = "Mike";
Id = 02; Name = "Tom"; ???
}
If possible to do this, what is the syntax? thanks
You completely misunderstood what a constructor is. A constructor is for one single object. It creates one single object. Thus you cannot set another record with it. That record will be a different object. You just set the values as arguments to constructor when you create another record.
So, should at least be like this -
public class MikesClass
{
public MikesClass(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
and in some distance place when creating multiple records/objects -
var m1 = new MikesClass(0,"name1");
var m2 = new MikesClass(1, "name2");
Using the code you specified above, each time you write:
MikesClass mc = new MikesClass();
you will get an object of type MikesClass with the Id property set to 1 and the Name property set to "Mike". Since each instance of MikesClass represents a single object, you cannot have multiple objects represented within it.
What you can do though, is modify your constructor to take the two values as parameters. Like this:
public MikesClass(int id, string name)
{
Id = id;
Name = name;
}
You can then use this code to create multiple MikesClass objects like so:
MikesClass mike = new MikesClass(1, "Mike");
MikesClass tom = new MikesClass(2, "Tom");
Hope this makes sense.
What you're showing is a constructor. It is run when you create an instance of the MikeClass class.
What you want is to create several instances. Maybe in an array?
MikeClass[] array = new MikeClass[2];
MikeClass mc = new MikeClass(); /first instance
mc.Id = 1;
mc.Name = "Mike";
array[0] = mc;
mc = new MikeClass(); //another instance
mc.Id = 2;
mc.Name = "Tom";
array[1] = mc;
};
This is using object initializer syntax:
MikeClass[] array = new MikeClass[] {
new MikeClass { Id = 1, Name = "Mike" }, //first instance
new MikeClass { Id = 2, Name = "Tom" } //another instance
};
You can also create a constructor for the MikeClass class that takes parameters:
public MikeClass(int id, string name) {
Id = id;
Name = name;
}
Then:
MikeClass[] array = new MikeClass[] {
new MikeClass(1, "Mike"),
new MikeClass(2, "Tom")
};
I have 2 types of string: Mer and Spl
// Example
string testMer = "321|READY|MER";
string testSpl = "321|READY|SPL";
Then I will split them:
var splitMer = testMer.Split('|');
var splitSpl = testSpl.Split('|');
I have an object to save them
public class TestObject
{
public int id { get; set; }
public string status { get; set; }
public string type { get; set; }
}
Question: How to convert the Array into the TestObject?
var converted = new TestObject
{
id = int.Parse(splitMer[0]),
status = splitMer[1],
type = splitMer[2]
};
You will need to add some error checking.
var values = new List<string> { "321|READY|MER", "321|READY|SPL" };
var result = values.Select(x =>
{
var parts = x.Split(new [] {'|' },StringSplitOptions.RemoveEmptyEntries);
return new TestObject
{
id = Convert.ToInt32(parts[0]),
status = parts[1],
type = parts[2]
};
}).ToArray();
You just need to use object initializers and set your properties.By the way instead of storing each value into seperate variables, use a List.Then you can get your result with LINQ easily.
var splitMer = testMer.Split('|');
var testObj = new TestObject();
testObj.Id = Int32.Parse(splitMer[0]);
testObj.Status = splitMer[1];
testObj.type = splitMer[2];
How about adding a Constructor to your Class that takes a String as a Parameter. Something like this.
public class TestObject
{
public int id { get; set; }
public string status { get; set; }
public string type { get; set; }
public TestObject(string value)
{
var valueSplit = value.Split('|');
id = int.Parse(valueSplit[0]);
status = valueSplit[1];
type = valueSplit[2];
}
}
Usage:
TestObject tst1 = new TestObject(testMer);
TestObject tst2 = new TestObject(testSpl);