Is there a way to create standard classes and objects in C # like php

In php we can create standard classes and objects like this

< ?php 

$ car = new stdClass;
$ car-> Color = 'black';
$ car-> type = 'sports';

print_r ($ car);
? >

Is there a similar way in C # .net ??? I am very new to C # who can help ???

+6
source share
3 answers

You can use Anonymous types in C #, for example: taken from the link:

 var v = new { Amount = 108, Message = "Hello" }; Console.WriteLine(v.Amount + v.Message); 

Pay attention to the β€œRemarks” section for their limitations (for example, can only be passed to an object), etc.

+10
source

C # is statically typed, so regular classes must be declared before using them. However, anonymous types allow you to declare classes based on initialization. After the declaration, neither the type nor the instance may be changed.

For a more dynamic approach, take a look at ExpandoObject , which allows you to dynamically add properties. This requires C # 4, and the link must be declared dynamic.

 dynamic car = new ExpandoObject(); car.Color = "Black"; car.Type "Sports"; 
+8
source

You can use anonymous types, but they are not exactly the same: http://msdn.microsoft.com/en-us/library/bb397696.aspx

C # is really all about strong typing, so weak support is, well, pretty weak. Depending on what you are actually doing here, an anonymous type may work, but in general you should create real classes when coding in C #. For your Car example above, I usually created a class. This is more code, but it is a C # way. PHP you can create an application, say, from 10 PHP files, but the same C # application will probably be 20-30 times.

+3
source

Source: https://habr.com/ru/post/910094/


All Articles