C create object from type

C create object from type

C# has a number of built-in reference types. They have keywords or operators that are synonyms for a type in the .NET library.

The object type

The object type is an alias for System.Object in .NET. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from System.Object. You can assign values of any type to variables of type object . Any object variable can be assigned to its default value using the literal null . When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. For more information, see Boxing and Unboxing.

The string type

The string type represents a sequence of zero or more Unicode characters. string is an alias for System.String in .NET.

Although string is a reference type, the equality operators == and != are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance.

The + operator concatenates strings:

This creates a string object that contains "good morning".

Strings are immutable—the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b . The memory that had been allocated for b (when it contained the string "h") is then eligible for garbage collection.

The [] operator can be used for readonly access to individual characters of a string . Valid values start at 0 and must be less than the length of the string :

In similar fashion, the [] operator can also be used for iterating over each character in a string :

String literals are of type string and can be written in two forms, quoted and @ -quoted. Quoted string literals are enclosed in double quotation marks ("):

String literals can contain any character literal. Escape sequences are included. The following example uses escape sequence \ for backslash, u0066 for the letter f, and
for newline.

The escape code udddd (where dddd is a four-digit number) represents the Unicode character U+ dddd . Eight-digit Unicode escape codes are also recognized: Udddddddd .

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:

Читайте также:  Acorp официальный сайт на русском

The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified Windows file name:

To include a double quotation mark in an @-quoted string, double it:

The delegate type

The declaration of a delegate type is similar to a method signature. It has a return value and any number of parameters of any type:

In .NET, System.Action and System.Func types provide generic definitions for many common delegates. You likely don’t need to define new custom delegate types. Instead, you can create instantiations of the provided generic types.

A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates. Delegates are the basis for Events. A delegate can be instantiated by associating it either with a named or anonymous method.

The delegate must be instantiated with a method or lambda expression that has a compatible return type and input parameters. For more information on the degree of variance that is allowed in the method signature, see Variance in Delegates. For use with anonymous methods, the delegate and the code to be associated with it are declared together.

The dynamic type

The dynamic type indicates that use of the variable and references to its members bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

Type dynamic behaves like type object in most circumstances. In particular, any non-null expression can be converted to the dynamic type. The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object . Therefore, type dynamic exists only at compile time, not at run time.

The following example contrasts a variable of type dynamic to a variable of type object . To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WriteLine statements. Copy the following code into an editor where IntelliSense is available. IntelliSense shows dynamic for dyn and object for obj .

Читайте также:  1С передать сообщение с сервера на клиент

The WriteLine statements display the run-time types of dyn and obj . At that point, both have the same type, integer. The following output is produced:

To see the difference between dyn and obj at compile time, add the following two lines between the declarations and the WriteLine statements in the previous example.

A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3 . However, no error is reported for dyn + 3 . The expression that contains dyn is not checked at compile time because the type of dyn is dynamic .

The following example uses dynamic in several declarations. The Main method also contrasts compile-time type checking with run-time type checking.

Types

Part of what makes C# programming (and .NET development in general) so easy is working with Types. C# and other .NET languages allow programmers to work directly with types, which represent the "type" of an object or structure, without working with instances.

.NET development with types is a powerful thing. So let’s look at something simple, taking a type and creating a new object from it.

New Instance

Normally you would create a new instance of an object with the C# new keyword. For example, say we want a new List object:

The variable myList would then hold a single instance of the List type. This is simple enough because we know the type of the object before hand. But C# variables can also be a type, for example:

So the variable myType does not hold an instance of an object, instead it holds a reference to the string type. Since the reference behaves like a variable, C# developers can type references in all sorts of ways, such as function parameters or in arrays.

A crucial part of working with variables is thus to be able to create a new object from a type-variable. Let’s try an example with creating a List object from a reference type.

Note that the CreateInstance function returns an object variable, so it needs to be cast into the proper type.

Conclusion

So what is the use of creating an object instance in such as complicated manner? Well like mentioned before, C# gives .NET developers the flexibility of working with type references as variables, which means programmers can pass them between functions and use them anywhere else that variables are used. This technique is especially powerful when combined with interfaces.

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type . How do you get a new object instance from a Type ?

Читайте также:  Auth что это значит

12 Answers 12

The Activator class within the root System namespace is pretty powerful.

There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:

Here are some simple examples:

The Activator class has a generic variant that makes this a bit easier:

Compiled expression is best way! (for performance to repeatedly create instance in runtime).

Statistics (2015, .net 4.5, x64):

Statistics (2015, .net 4.5, x86):

Statistics (2017, LINQPad 5.22.02/x64/.NET 4.6):

Statistics (2019, x64/.NET 4.8):

Statistics (2019, x64/.NET Core 3.0):

One implementation of this problem is to attempt to call the parameter-less constructor of the Type:

Here is the same approach, contained in a generic method:

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles , then pass the parameter as Vehicles.Car which returns object of type Car . Like this you can create any instance of any class dynamically.

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type . For that you can use the below code

And you can get the instance by calling the above method.

If this is for something that will be called a lot in an application instance, it’s a lot faster to compile and cache dynamic code instead of using the activator or ConstructorInfo.Invoke() . Two easy options for dynamic compilation are compiled Linq Expressions or some simple IL opcodes and DynamicMethod . Either way, the difference is huge when you start getting into tight loops or multiple calls.

Wouldn’t the generic T t = new T(); work?

If you want to use the default constructor then the solution using System.Activator presented earlier is probably the most convenient. However, if the type lacks a default constructor or you have to use a non-default one, then an option is to use reflection or System.ComponentModel.TypeDescriptor . In case of reflection, it is enough to know just the type name (with its namespace).

Example using reflection:

Example using TypeDescriptor :

Without use of Reflection:

Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using

I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)

With generic method you can require that the type implements New().

With non-generic assume the type has a default constructor and catch an exception if it doesn’t.

Ссылка на основную публикацию
Adblock detector