Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "var obj = new Object" Equivalent in C#

Is there an easy way to create and Object and set properties in C# like you can in Javascript.

Example Javascript:

var obj = new Object;

obj.value = 123476;
obj.description = "this is my new object";
obj.mode = 1;
like image 566
PercivalMcGullicuddy Avatar asked Jul 08 '11 14:07

PercivalMcGullicuddy


People also ask

What is equivalent of JS object in C#?

Javascript "var obj = new Object" Equivalent in C#

What is new object () in JavaScript?

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

What is JavaScript object variable?

Variable object When a JavaScript function is executed, apart from the global execution context which have already been created, an execution context associated with the function is created. A variable object is simply an object storing data related to an execution context.

How do you create a new function in JavaScript?

The syntax for creating a function: let func = new Function ([arg1, arg2, ... argN], functionBody); The function is created with the arguments arg1...


2 Answers

try c# anonymous classes

var obj = new { 
    value = 123475, 
    description = "this is my new object", 
    mode = 1 };

there are lots of differences though...

@Valera Kolupaev & @GlennFerrieLive mentioned another approach with dynamic keyword

like image 145
Andrew Florko Avatar answered Oct 27 '22 11:10

Andrew Florko


In case, if you want to create un-tyed object use ExpandoObject.

dynamic employee, manager;

employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

manager = new ExpandoObject();
manager.Name = "Allison Brown";
manager.Age = 42;
manager.TeamSize = 10;

Your other option is to use anonymous class , but this will work for you, only if you would use it in the scope of the method, since the object type information can't be accessed from outside of the method scope.

like image 42
Valera Kolupaev Avatar answered Oct 27 '22 10:10

Valera Kolupaev