473,379 Members | 1,542 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,379 software developers and data experts.

Calling new, when i dont know type.

I have a situation where i have a base class and a sub-class. A null instance of the sub-class is passed into a function. The function needs to create a new instance of the sub-class, but the function only has knowledge of the base class, not the sub-class

So is there a way to get the function to create a new instance of the sub-class without actually using 'new SubClass()

Let me demonstrate what i want to do. Below, in my situation, the function CreateInstanceOfClass cant actually declare a new instance of SubClass, because it has no knowledge of it. But it still needs to create a new instance of it. If i create a new instance of BaseClass, non of SubClass's overridden functions will get called

public class BaseClas

public virtual int MyFunction() {return 0;
public class SubClass : BaseClas

public override int MyFunction() {return 3;
public class DoStuf

public void CreateInstanceOfClass(BaseClass subClass

//Need to create an instance of SubClass, but cant actually declare a new SumeSubClas
subClass = new typeof(subClass)
int ret = subClass.MyFunction(); //I want 3, not

Any Ideas?
Nov 15 '05 #1
3 2502
You can't do what you want to do. In CreateInstanceOfClass, you're getting a
BaseClass reference passed in. Now, if you had a real instance of a subclass
passed in, you'd be able to call GetType() on it, and then use
Activator.CreateInstance() to create another instance (though it would be
slow to do so).

'null' doesn't have any associated type, so there's no way for the function
to find out what kind of variable you had it in.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"john" <an*******@discussions.microsoft.com> wrote in message
news:DF**********************************@microsof t.com...
I have a situation where i have a base class and a sub-class. A null instance of the sub-class is passed into a function. The function needs to
create a new instance of the sub-class, but the function only has knowledge
of the base class, not the sub-class.
So is there a way to get the function to create a new instance of the sub-class without actually using 'new SubClass()'
Let me demonstrate what i want to do. Below, in my situation, the function CreateInstanceOfClass cant actually declare a new instance of
SubClass, because it has no knowledge of it. But it still needs to create a
new instance of it. If i create a new instance of BaseClass, non of
SubClass's overridden functions will get called.
public class BaseClass
{
public virtual int MyFunction() {return 0;}
}

public class SubClass : BaseClass
{
public override int MyFunction() {return 3;}
}

public class DoStuff
{
public void CreateInstanceOfClass(BaseClass subClass)
{
//Need to create an instance of SubClass, but cant actually declare a new SumeSubClass subClass = new typeof(subClass);
int ret = subClass.MyFunction(); //I want 3, not 0
}
}

Any Ideas?

Nov 15 '05 #2
Hi john,

You might find reflection useful for what you want to do. You need to at
least know the name of the sub class as a string to get the Type you need:

Type mytype = Type.GetType("SubClass, MyAssembly");

or you might know the value of mytype by some other means (a lookup list for
instance)

Then you can invoke the constructor via reflection:

BaseClass subClass = (BaseClass)mytype.InvokeMember("",
BindingFlags.CreateInstance, null, null, new Object[]{});
int ret = subClass .MyFunction(); // will return 3

Cheers

Doug Forster
"john" <an*******@discussions.microsoft.com> wrote in message
news:DF**********************************@microsof t.com...
I have a situation where i have a base class and a sub-class. A null instance of the sub-class is passed into a function. The function needs to
create a new instance of the sub-class, but the function only has knowledge
of the base class, not the sub-class.
So is there a way to get the function to create a new instance of the sub-class without actually using 'new SubClass()'
Let me demonstrate what i want to do. Below, in my situation, the function CreateInstanceOfClass cant actually declare a new instance of
SubClass, because it has no knowledge of it. But it still needs to create a
new instance of it. If i create a new instance of BaseClass, non of
SubClass's overridden functions will get called.
public class BaseClass
{
public virtual int MyFunction() {return 0;}
}

public class SubClass : BaseClass
{
public override int MyFunction() {return 3;}
}

public class DoStuff
{
public void CreateInstanceOfClass(BaseClass subClass)
{
//Need to create an instance of SubClass, but cant actually declare a new SumeSubClass subClass = new typeof(subClass);
int ret = subClass.MyFunction(); //I want 3, not 0
}
}

Any Ideas?

Nov 15 '05 #3
Hello.

Why not to create an abstract method 'BaseClass CreateInstance( .... pars
.... )' in 'BaseClass' and implement it in each subclass.

Best regards!
Nov 15 '05 #4

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

Similar topics

5
by: Chris | last post by:
Hi I have a scenario where I've created another AppDomain to dynamically load a DLL(s) into. In this newly loaded DLL I want to call a static method on a class. The problem arise is that I have...
2
by: William Payne | last post by:
Hello, consider these following two classes. A base class, class MDIChildWindow, and a class inherting from that base class, class Document. In the static base member function callback() I obtain a...
6
by: Eric Lilja | last post by:
Hello, I have a std::vector storing pointers to an abstract base class OptionBase. OptionBase is not templated but I am deriving a template class called Option from OptionBase. The class Option has...
5
by: niftyhawk | last post by:
Hi, Can anybody give me a simple example of how to Call Web Services from Mozilla based Browsers ? I can call web services from IE browser using web service behavior file, without any problems....
5
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS...
5
by: Simon Harris | last post by:
Hi All, I am trying to call a method in a web form, from an event fired in a user control. My user control displays a map, which has a link button to enlarge/shrink the map. When the user...
2
by: ramaseshan.k | last post by:
Hi I am c# newbie coming from c++ background. I need to call a COM object(which was written in VC++) from my c# program. The c++ application(Let's call it abc) has an .ODL file that defines...
10
by: SQACPP | last post by:
Hi, I try to figure out how to use Callback procedure in a C++ form project The following code *work* perfectly on a console project #include "Windows.h" BOOL CALLBACK...
7
by: =?Utf-8?B?UVNJRGV2ZWxvcGVy?= | last post by:
I have a C# logging assembly with a static constructor and methods that is called from another C# Assembly that is used as a COM interface for a VB6 Application. Ideally I need to build a file...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: 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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.