3

I am having a problem creating an object and setting/getting the values. The purpose of this is to return data from a Model to a Controller.

Disclaimer: Im new to C#

Can anyone show me the right way to do it?

I have tried these ways but I keep getting the error:

object o = new { test = "cat" };
o.test = "dog";

Object o = new { test = "cat" };
o.test = "dog";

object o = new Object();
o.test = "dog";

// I also tried
object o = new Object();
o["test"] = "dog";
6
  • What are you actually trying to do? Commented Jan 24, 2013 at 16:16
  • 1
    Not trying to be mean, but really? Commented Jan 24, 2013 at 16:17
  • Why not use a dictionary? Commented Jan 24, 2013 at 16:21
  • 1
    Can I ask you why you are not creating a class and instantiating it first? Commented Jan 24, 2013 at 16:21
  • I was looking for the simplest answer Commented Jan 24, 2013 at 16:30

8 Answers 8

8

You need to instantiate a class in C#. Creating objects out of the blue (like in JavaScript) isn't possible in C#.

For example, the class would look like this:

public class MyClass {
  public string test { get; set; }
}

MyClass o = new MyClass { test = "cat" };

Update: Since .NET 3.5 you actually can create objects like this:

var o = new { test = "cat" };
Console.WriteLine(o.test);

However, after creating them you can't add or remove properties.

Sign up to request clarification or add additional context in comments.

6 Comments

Oh for real? That is crazy
He has been creating real objects (using an anonymous type), he's just storing them as an object and therefore can't do much of anything with them.
Your edit is just wrong. It's an anonymous type, which is not a dynamic object; in fact it's immutable. var was introduced in .NET 3.5, not 4.5, as were anonymous types. A real dynamic object would be ExpandoObject, and that was introduced in 4.0. It's a shame that such a completely wrong answer is getting pity upvotes as well.
@Servy You're right. I was thinking of dynamic (which was introduced in 4.5 IIRC) but it's actually an anonymous type. (The OP didn't say anything about dynamic objects though.)
@SebastianKrysmanski dynamic was introduced in 4.0., not 4.5.
|
6

JREAM, your basic premise and understanding of C# objects is probably a little bit flawed which is what is causing your confusion.

"In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object." http://msdn.microsoft.com/en-us/library/9kkx3h3c%28v=vs.110%29.aspx

That being said, it is preferable to use a defined type rather than object whenever possible. In your case, your objects should really be classes, which then in turn makes then reference types that you can consume.

public class O
{
    public string test { get; set; }
}

var newO = new O() { test = "cat" };
newO = "dog";

Here, we create a new class, 'O'. We have a single property inside of this class. We can then instantiate the class and access the properties inside of it. Once it is instantiated, we can then access the property as much as we want and reassign new values to it. Hope that helps.

3 Comments

anonymous types in no way violate strong typing.
Agreed, it doesn't violate it at all. I just think it lends to more clearly defined strongly typing, from a readability perspective. I agree, it most certainly does not violate it and I've removed that line from my answer.
Either your code is statically typed or it's not. It's not really something that's on a spectrum.
3

If you are looking for a Key,Value pair you could easily use a Dictionary;

using System.Collections.Generic;

Dictionary<string, string> kv = new Dictionary<string, string>() {
 {"Key1","Value1"}, {"Key2","Value2"}, {"Key3","Value3"}
};

And retrieve as;

string Val1 = kv["Key1"];

And add key, values as;

kv.Add("Key4","Value4");

Comments

3

It looks like what you are trying to create is an anonymous type. Anonymous types are great because they provide a quick and convenient way to create an object without having to define a type.

Try this:

var o = new { test = "cat" };

At that point, you will be able to access the properties of the anonymous type like so:

o.test = "dog";
MessageBox.Show(o.test);  //shows "dog"

1 Comment

I can't see anything wrong with this. I think the down voter should explain/comment why.
2

An object doesn't have those properties or fields. To access those fields make the variable dynamic.

dynamic o = new { test = "cat" };
Console.WriteLine(o.test );

Oh, btw o["test"] wouldn't work.. o isn't an assoc array in JavaScript or C#'s dictionary.. it is an anonymous object.

2 Comments

Could you provide an example
you only need to use var here, no need to throw dynamic at this. Also, the last line won't work even with dynamic.
1

Normally, you create a class and initialize an instance of this class; but the following works anyway.

Beware that, even if test is not declared, it will still build; but you will have an exception at runtime.

dynamic temp = ((dynamic)o).test;

Comments

1
new { test = "cat" };

You are trying to create an anonymous object with test property, which doesn't seem to be what you want. If you want to initialize custom properties use next syntax

var customer = new Customer {Name = "Ilya"};

Which will be translated by compiler into

var customer = new Customer();
customer.Name = "Ilya";

Note you should define your custom class like

public class Customer 
{
    public string Name { get; set; }
}

Comments

1

If you want an arbitrary mapping of a string to a value then you should use a Dictionary.

Dictionary<string, string> lookup = new Dictionary<string, string>();
lookup.Add("test", "dog");
//add other pairs.

string value = lookup["test"]; //value will be "dog"

The code new { test = "cat" }; creates an instance of a new anonymous type with one property (test) and a set value. Anonymous types in C# are immutable, so you won't be able to set that property to anything else once it's created.

The reason you can't access it properly is that you are storing it in an object. Since object doesn't have any properties, the compiler is "losing" the knowledge that the object has that property. You can use var to ensure that the variable is of the proper type (which is an anonymous type) which will allow you to use the propery:

var obj = new { test = "cat" };
string value = obj.test;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.