Reputation: 12027
After practicing with JS for some time I've moved to C#. I'm trying to create an object with some properties in C#. In JS I could do it like this:
var person = {
fname : "",
lname : "",
id : ""
}
I want to create something similar to this in C#. I've watched some tuts and I'm a little confused. There are classes, dictionaries, hashtables. I don't know where to start.
If there is a way to do it without using a constructor I'd prefer to use it. Cus I won't be changing the values and using a constructer is a pain. Object will have like 10+ property so typing them in a single line with the correct order... uh, no.
Upvotes: 1
Views: 1508
Reputation: 13234
In addition to the answers already provided, c# allows both anonymous types and it supports dynamic types. So taking the example you gave, in c# you can do:
Anonymous type:
var person = new {
fname = "first",
lname = "last",
id = "123"
};
Console.WriteLine(person.lname);
Dynamic type:
dynamic anotherPerson = new System.Dynamic.ExpandoObject();
anotherPerson.FirstName = person.lname;
Console.WriteLine(anotherPerson.FirstName);
anotherPerson.PrintPerson = (Action<dynamic>)((p => Console.WriteLine("[{0}] {1}. {2}", p.id, p.lname, p.fname)));
anotherPerson.PrintPerson(person);
These examples are a little contrived. There are specific circumstances where they come in very handy. However unless you really need it, it is preferred to create strongly typed classes. They provide you with a public interface contract that can be verified by the compiler. Also in most scenarios the runtime cost for dynamic types will be substantially higher.
Upvotes: 2
Reputation: 8878
In c# (4.0 and above) you can use named and optional parameters (http://msdn.microsoft.com/en-us/library/dd264739.aspx), so you can keep your class immutable.
Upvotes: 1
Reputation: 34844
You can create a C# class with properties, so you can set the properties on separate lines similar to the expando properties syntax of JavaScript, like this:
public class Person
{
public string fname { get; set; }
public string lname { get; set; }
public int id { get; set; }
}
Now you can invoke the class and set the properties, like this:
var person = new Person();
person.fname = "John";
person.lname = "Jones";
person.id = 7;
Also, you can use the object initializer syntax, like this:
var person = new Person {
fname = "John",
lname = "Jones",
id = 7
};
Note: C# is strongly typed so you cannot change the type of a value in a property like you can in JavaScript.
Upvotes: 0
Reputation: 3067
You could create a class "Person"
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
}
And then instantiate a new Person like so:
var p = new Person {
FirstName = "",
LastName = "",
ID = 1
};
And do what you need with that Person
Upvotes: 0