473,385 Members | 1,730 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

purpose of CreateInstance<T>

Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?

i don't understand how this method helps anything.

dan
Jun 27 '06 #1
8 4361
Dan Holmes wrote:
Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?

i don't understand how this method helps anything.

dan

CreateInstance<T> is an example of a generic method. The generic
parameter T enables you to invoke it with different data types eg:

CreateInstance<CustomDataType>()
CreateInstance<string>()
CreateInstance<T>()

An advantage of a generic method is that you can implement the
behaviour/algorithm once and apply it to different types.

Hope this helps.

A

Jun 27 '06 #2
antoan wrote:
Dan Holmes wrote:
Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?

i don't understand how this method helps anything.

dan

CreateInstance<T> is an example of a generic method. The generic
parameter T enables you to invoke it with different data types eg:

CreateInstance<CustomDataType>()
CreateInstance<string>()
CreateInstance<T>()

An advantage of a generic method is that you can implement the
behaviour/algorithm once and apply it to different types.

Hope this helps.

A

I guess i figured the non-generic version could do all of that too.
Jun 27 '06 #3
On Tue, 27 Jun 2006 17:38:06 -0400, Dan Holmes <da*******@bigfoot.com>
wrote:
antoan wrote:
Dan Holmes wrote:
Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?

i don't understand how this method helps anything.

dan

CreateInstance<T> is an example of a generic method. The generic
parameter T enables you to invoke it with different data types eg:

CreateInstance<CustomDataType>()
CreateInstance<string>()
CreateInstance<T>()

An advantage of a generic method is that you can implement the
behaviour/algorithm once and apply it to different types.

Hope this helps.

A

I guess i figured the non-generic version could do all of that too.


I really cannot see the point of the generic version of CreateInstance.
All it appears to be to me is an unsafe way to call new T() as it
doesn't enforce that T has a parameterless constructor.

Thus:
String a = Activator.CreateInstance<String>();
will compile but you just get a run-time error.

But if you knew the type to put in the generic why not just call:
MyClass a = new MyClass()
Jun 27 '06 #4
Dan Holmes <da*******@bigfoot.com> wrote:
Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?

i don't understand how this method helps anything.


It's the implementation of ": new()" and "new T()". It also leaves an
avenue to the CLR folks to dynamically bind to the corresponding
constructor so that reflection doesn't have to be used.

It isn't currently optimized (check it out with SOS and !u) - but that
path is available to future runtimes.

Test program:

---8<---
using System;

class App
{
class A {}
class B : A {}

static void Main()
{
A a = Activator.CreateInstance<A>();
B b = Activator.CreateInstance<B>();
}
}
--->8---

The contents of App.Main, unassembled with WinDbg, SOS, !u:

---8<---
mov ecx,0x9230f8
(MD: System.Activator.CreateInstance[[App+A, Test]]())

call mscorlib_ni+0x2edd58 (793add58)
(System.Activator.CreateInstance[[System.__Canon, mscorlib]](),
mdToken: 06000399)

mov ecx,0x9231b0
(MD: System.Activator.CreateInstance[[App+B, Test]]())

call mscorlib_ni+0x2edd58 (793add58)
(System.Activator.CreateInstance[[System.__Canon, mscorlib]](),
mdToken: 06000399)

ret
--->8---

You can see there that the actual method called for both invocations of
CreateInstance is the preJITted one at 793add58, so it must be using
reflection in order to get the job done.

-- Barry

--
http://barrkel.blogspot.com/
Jun 27 '06 #5
Chris Chilvers wrote:
On Tue, 27 Jun 2006 17:38:06 -0400, Dan Holmes <da*******@bigfoot.com>
wrote:
antoan wrote:
Dan Holmes wrote:
Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?

i don't understand how this method helps anything.

dan

CreateInstance<T> is an example of a generic method. The generic
parameter T enables you to invoke it with different data types eg:

CreateInstance<CustomDataType>()
CreateInstance<string>()
CreateInstance<T>()

An advantage of a generic method is that you can implement the
behaviour/algorithm once and apply it to different types.

Hope this helps.

A

I guess i figured the non-generic version could do all of that too.


I really cannot see the point of the generic version of CreateInstance.
All it appears to be to me is an unsafe way to call new T() as it
doesn't enforce that T has a parameterless constructor.

Thus:
String a = Activator.CreateInstance<String>();
will compile but you just get a run-time error.

But if you knew the type to put in the generic why not just call:
MyClass a = new MyClass()

It is simply a factory method that allows you to deffer the
specification of the data type it acts/produces until you actually need
to declare it eg

MyClass Activator.CreateInstance<Activator>();

The whole point here is that you can REUSE the same generic method to
create strongly typed instances of the data type you want by way of
specifying the generic type parameter which in this example is
"MyClass". The advantage of dealing with strong types as opposed to
object(s) as in the case of:

object Activator.CreateInstance(Type);

is that you dont have to suffer performance penalties by having to box -
unbox value types from the heap as well casting back to the required
type from object.

As the sdk docs say it regarding the method discussed: "Creates an
instance of the specified type using the constructor that best matches
the specified parameter".

you should probably check out the the msdn generics guide:

http://msdn.microsoft.com/library/de...p_generics.asp

Jun 28 '06 #6
You are missing the point somewhat.

If you are specifying the type in the Generic call, like so:

MyClass mc = Activator.CreateInstance<MyClass>();

Why not just do:

MyClass mc = new MyClass();

Yes, the CreateInstance<T> is type safe, but you have to declare that
type at compile time. If you have to declare the type, then you might as
well call the constructor directly.

If you call Activator.CreateInstance, then you also run the risk of the
type not having a default constructor. If you call the constructor
directly, you will get a compile-time error, as opposed to a run time error.
Compile time errors are ALWAYS preferable.

That being said, I can't see a reason to EVER use
Activator.CreateInstance<T>.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"antoan" <an****@antoan.plus.com> wrote in message
news:44***********************@ptn-nntp-reader01.plus.net...
Chris Chilvers wrote:
On Tue, 27 Jun 2006 17:38:06 -0400, Dan Holmes <da*******@bigfoot.com>
wrote:
antoan wrote:
Dan Holmes wrote:
> Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?
>
> i don't understand how this method helps anything.
>
> dan

CreateInstance<T> is an example of a generic method. The generic
parameter T enables you to invoke it with different data types eg:

CreateInstance<CustomDataType>()
CreateInstance<string>()
CreateInstance<T>()

An advantage of a generic method is that you can implement the
behaviour/algorithm once and apply it to different types.

Hope this helps.

A

I guess i figured the non-generic version could do all of that too.


I really cannot see the point of the generic version of CreateInstance.
All it appears to be to me is an unsafe way to call new T() as it
doesn't enforce that T has a parameterless constructor.

Thus:
String a = Activator.CreateInstance<String>();
will compile but you just get a run-time error.

But if you knew the type to put in the generic why not just call:
MyClass a = new MyClass()

It is simply a factory method that allows you to deffer the specification
of the data type it acts/produces until you actually need to declare it eg

MyClass Activator.CreateInstance<Activator>();

The whole point here is that you can REUSE the same generic method to
create strongly typed instances of the data type you want by way of
specifying the generic type parameter which in this example is "MyClass".
The advantage of dealing with strong types as opposed to object(s) as in
the case of:

object Activator.CreateInstance(Type);

is that you dont have to suffer performance penalties by having to box -
unbox value types from the heap as well casting back to the required type
from object.

As the sdk docs say it regarding the method discussed: "Creates an
instance of the specified type using the constructor that best matches the
specified parameter".

you should probably check out the the msdn generics guide:

http://msdn.microsoft.com/library/de...p_generics.asp


Jun 28 '06 #7
That being said, I can't see a reason to EVER use
Activator.CreateInstance<T>.


You may be using it without knowing it. The compiler compiles new T()
for a generic type parameter T to a call to
Activator.CreateInstace<T>(). Try running ILDASM on the following

class Foo<T> where T : new() { T t = new T(); }
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jun 28 '06 #8
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com>
wrote:
That being said, I can't see a reason to EVER use
Activator.CreateInstance<T>.


The compiler needs it for generic new() constraints.

-- Barry

--
http://barrkel.blogspot.com/
Jun 28 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Neil Zanella | last post by:
Hello, I would like to ask how come the design of C++ includes std::pair. First of all I don't think many programmers would use it. For starters, what the first and second members are depends...
7
by: R. Anbeeswaran | last post by:
Hi All, void main() { const int i = 20; int *p = const_cast<int*>(&i); *p = 40; cout <<"i="<< i <<"\t"<<"*p="<<*p<<"\n"; }
6
by: Jegger | last post by:
Hello! We have following situation; network with 100 users, aplication developed in Access, user DB deployed on SQL Server. Is it better to create query inside aplication (with code) and then...
11
by: Jamie Burns | last post by:
Hello, I just did a simple benchmark: for (xx=0;xx<100000;xx++) { rDerived* derived = dynamic_cast<rDerived*>(object); if (derived) derived->setValue(message.data.messageSetInt.value); } ...
0
by: John Lafrowda | last post by:
Dear all, here is a simple problem that I cannot overcome: I'm trying to write a client/server application in Visual Basic .net. The server is an executable (.exe) project, the clients are class...
6
by: msdnuniv | last post by:
Hello everybody, since days i try to convert Unicode-Strings in VB.NET to ANSI which should be processable in VB6 and converted to unicode again. It should be possible with any codepage, e.g....
5
by: Rainer Queck | last post by:
Hello NG, Is it possible to share the settings of an application with a class libreary? In my case I have a application and a set of different reports (home made) put into a class library. The...
4
by: Anastasios Hatzis | last post by:
I'm looking for a pattern where different client implementations can use the same commands of some fictive tool ("foo") by accessing some kind of API. Actually I have the need for such pattern for...
2
by: Markus Dehmann | last post by:
I have two integers i1 and i2, the second of which is guaranteed to be between 0 and 99, and I encode them into one double: double encoded = (double)i1 + (double)i2 / (double)100; So, for...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.