C # - Creating an object

I am a PHP programmer for a while. Two days ago, I went for an interview where they let me know what to do in ASP.NET (C #). I would really like to get out of php's sphere of influence and learn a decent language that can challenge me. So I have a question

Do I need to create instances at runtime? In php, I can do something like this ...

class SomeObject {} $objString = "SomeObject"; $objInstance = new $objString(); 

I can not do this in C #, maybe it will be a compiled language. In C #, I need to create a Factory template that will create objects. It also means that if I need to instantiate 10 objects in Factory, then there will be 10 if statements, which are ugly.

I found an Activator object with its Activator::createInstance() method, but I could not get it to work. There is also Reflection, but both of them (as I know) are a performance impact.

So, is there a way to dynamically create objects, or can it be in C #, can I immediately create all the objects that my program will use, which is really tempting?

EDIT

Ok, so let's say that I have 5 objects that are used in 5 different cases. I run the program, the program estimates that it needs one of these objects and creates it. The other four are never created. I am closing the program.

The second time I run the program with different parameters, and 2 of these 5 objects are created, the other three have never appeared.

This is easy in PHP. Activate the activator and other tools aside, is it good to create all 5 objects in the C # world when I know that maybe only one of them will be used?

+6
source share
4 answers

I don't know if my question was wrong, but creating an object of your SomeObject class in C # is as simple as the following:

 var obj = new SomeObject(); 

Using Activator -Class, it should look like sth. like one of the following

 var obj2 = Activator.CreateInstance(typeof(SomeObject)); var obj3 = Activator.CreateInstance<SomeObject>();` var someObjType = Type.GetType("SomeObject"); // if you have to use a string var obj4 = Activator.CreateInstance(someObjType); 

Note that using Activator -Class for triggering objects is not required in most cases. The first example is the standard way if you know the Type class in compiletime.

UPDATE

regarding your update, since I don't know the details of what comes to my mind, this is lazy instanciation. Since everything, including the entry point of your application, is an object in C #, you can solve the problem using properties using fields with support, for example, in the following example

 class Program { // backing fields private SomeObject obj1; private SomeObject obj2; private SomeObject obj3; private SomeObject obj4; private SomeObject obj5; // this way, obj1 only gets instanciated when needed public SomeObject Obj1 { get { if (obj1 == null) { obj1 = new SomeObject(); } return obj1; } } // same for the other objects [...] } 

I am concerned about the memory usage of your object, I recommend that you learn how to correctly implement IDisposable

UPDATE 2

To provide the opportunity recommended in the comments from @Mad Sorcerer, you can return the fields using Lazy -Class, which requires some effort on your shoulder, the effect is the same as in the previous update.

 class Program { // Lazy backing fields private Lazy<SomeObject> obj1 = new Lazy<SomeObject>(); private Lazy<SomeObject> obj2 = new Lazy<SomeObject>(); private Lazy<SomeObject> obj3 = new Lazy<SomeObject>(); private Lazy<SomeObject> obj4 = new Lazy<SomeObject>(); private Lazy<SomeObject> obj5 = new Lazy<SomeObject>(); // this way, obj1 only gets instanciated when needed public SomeObject Obj1 { get { return obj1.Value; } } // same for the other objects [...] } 
+4
source

Yes, you can dynamically create objects in C #. But not as easy as in PHP.

As you find, there is Activator . It works great when you use it correctly. :) There's also direct reflection ( Activator also based on reflection). Both are slow at least use.

Using the Expression type, you can cache the logic to instantiate an object. It still slows down for the first time, but if you plan to repeatedly create the same type of object, this approach works well (and if not, the fact that it slows down through Activator doesn't matter :)).

However, most of the time you do not need to create objects dynamically, as in your example. A strong compilation type check in C # should be used, not excluded. Writing code that creates objects for which the type is already known at compile time is the most efficient and most secure for types.

For those few times when you need dynamic behavior, this is possible.

+5
source

So, what is the PHP code ... you choose which class should create its name as a string?

You need to look at the type first, and then create it using Activator.

 Type classType = Type.GetType("SomeObject"); object instance = Activator.CreateInstance(classType); 

You can find its constructor and call it, instead using a reflection that looks more like this

 Type classType = Type.GetType("SomeObject"); var ctorInfo = classType.GetConstructor(Type.EmptyTypes); object instance = ctorInfo.Invoke(new object[] {}); 

and you can cache the constructor as a delegate, which eliminates the performance limitation that arises from material search #

Note that Type.GetType has some of its problems. The above code will work if SomeObject is in the System namespace. You may need to add a namespace, class, and sometimes assembly. In any case, it is safer to use AssemblyQualifiedName .

+2
source

There are several ways to instantiate a class in C #.

The usual way is to simply use new :

 MyType myInstance = new MyType(); 

To dynamically create objects based on their name, for example, Activator.Createinstance() works, but you need to know the assembly where this class is defined so that you can correctly create this instance.

However, especially if you are just starting out, I would not do this. C # is a statically typed language, which means that type resolution is performed at compile time.

Also, consider that the IDE, Visual Studio, will help you a lot, as it can scan files in your project and know the type of each member that you enter into your code.

Static type languages ​​help to avoid the exact problems that arise in purely dynamic languages: they force you to be consistent, because you have to be explicit in your declaration (although C # with the var keyword can help a lot in preventing this usually required verbosity )

So, the whole point is to make sure that you declare all types that you will need in your application.

If you need a specific member of a class to receive data from several other classes, you can use inheritance to create a base class that others inherit some behavior or use Interfaces to describe common members for different types. Each has its own advantages and disadvantages .

If you are working with C # just by experimenting, I would recommend getting LINQpad . This can help you experiment while learning.

I would also stay away from anything that was not canonical: first understand the idiomatic C # before going too deep, trying to make stuff at runtime.

One area you can explore is the dynamic type. It's not as flexible as what you expect from a truly dynamic language, but it is a way to deal with type uncertainty.
However, it has a performance flaw and should be avoided if you want to use Intellisense in Visual Studio and want to use the usual type checking that the IDE and the compiler can provide.

+1
source

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


All Articles