473,769 Members | 2,063 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics


Hi all,

I need some help in understanding how to use Generics. I have a class
based on a user control that can be put on any Container at runtime, I
want to be able to call a method on the parent class without knowing the
type of the parent class, can this be done with C#?

I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.


An example would be

public class MyClass : UserControl
{

public void SomethingChange d()
{
// this method is bound to an event somewhere

// call the parent class method, I don't care what type the parent
class is just that is has the MyCustomMethod( ) method.

if (this.Parent.Ge tType().GetMemb er("MyCustomMet hod").GetLength (0) > 0)
this.parent.MyC ustomMethod(thi s)
}

}
thanks for all the help
Nov 28 '05 #1
7 3512
Gene,
I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.


No I don't think generics will help you here. If you author the
controls you can make them implement an interface where the
MyCustomMethod is defined (or derive from a common base class).
Otherwise you need late binding with Reflection.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 28 '05 #2
"Gene Vital" <no********@msn ew.com> a écrit dans le message de news:
%2************* ***@TK2MSFTNGP0 9.phx.gbl...

| I need some help in understanding how to use Generics. I have a class
| based on a user control that can be put on any Container at runtime, I
| want to be able to call a method on the parent class without knowing the
| type of the parent class, can this be done with C#?
|
| I thought this was what Generics was supposed to be all about but I have
| spent the whole day Googling and I can't find a way to do this in C#.

What you describe is not generics, it is polymorphism. Generics allows you
to write strictly typed code that applies to many different types, but that
can be written once only. Each time you use a generic type, you are not
deriving from a base class, you are actually using classes that are siblings
to each other. You cannot assign a parameterised instance of a generic class
to a differently parameterised instance. You must usually know the full type
of a generic instance in order to manipulate it, unless you have
methods/properties declared in a non-generic base class and that are
overridden in the generic derivative.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Nov 28 '05 #3
I'm afraid generics won't help you much here, but still you're not far from
the solution.
You can use reflection, which you've used in your example, to do this.

MethodInfo myCustomMethod= this.Parent.Get Type().GetMetho d("MyCustomMeth od",new
Type[] { this.GetType() });
if (myCustomMethod !=null)
{
myCustomMethod. Invoke(this.Par ent,new object[] { this });
}

Regards,
Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 28 '05 #4
Hi Gene,

No, this is not what Generics are used for. A Generic class is a class that
takes one or more type parameters. When a Generic class is compiled, it uses
the type(s) passed to it, and is strongly typed.

What you're talking about is reflection, which is the discovery of
characteristics of a type. From what I gather from your description, the
only thing known about the container Control for your Control is that it is
a Control, which isn't going to tell you anything about whether or not it
has a member defined that is a Method of the description you're looking for.
Therefore, you need to use reflection to find out.

The code you posted is close to the solution, but makes several fatal
assumptions. First, the return value of Type.GetMember( ) is an array of
System.Reflecti on.MemberInfo, but you are treating it as if it is a single
value. All you probably need to know is whether or not the Member Method
exists, and what type to cast the container to in order to properly access
the Member. So, what you need to do is first determine the type:

System.Type t = this.Parent.Get Type();

You need to store this in order to use it for casting if the Member exists.
Otherwise, you have to call GetType() twice.

Next, check to see whether the Member exists:

if (t.GetMember("M yCustomMethod") ) != null
{
t.InvokeMember( ("MyCustomMetho d", BindingFlags.In vokeMethod, null,
this.Parent, new Object[] {this});
}

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
If you push something hard enough,
it will fall over.
- Fudd's First Law of Opposition

"Gene Vital" <no********@msn ew.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..

Hi all,

I need some help in understanding how to use Generics. I have a class
based on a user control that can be put on any Container at runtime, I
want to be able to call a method on the parent class without knowing the
type of the parent class, can this be done with C#?

I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.


An example would be

public class MyClass : UserControl
{

public void SomethingChange d()
{
// this method is bound to an event somewhere

// call the parent class method, I don't care what type the parent class
is just that is has the MyCustomMethod( ) method.

if (this.Parent.Ge tType().GetMemb er("MyCustomMet hod").GetLength (0) > 0)
this.parent.MyC ustomMethod(thi s)
}

}
thanks for all the help

Nov 28 '05 #5
I don't have vs2005 here to test this, but try this......
public class MyClass <TParent> : UserControl
{
protected SomeEvent(objec t sender, EventARgs e)
{
TParent parent = this.Parent as TParent;
parent.MyCustom Method();
}
}

public class MyParent
{
private MyChild<MyParen t> child;

public MyCustomMethod( ) {...}
}

--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
"Gene Vital" <no********@msn ew.com> wrote in message
news:#3******** ******@TK2MSFTN GP09.phx.gbl...

Hi all,

I need some help in understanding how to use Generics. I have a class
based on a user control that can be put on any Container at runtime, I
want to be able to call a method on the parent class without knowing the
type of the parent class, can this be done with C#?

I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.


An example would be

public class MyClass : UserControl
{

public void SomethingChange d()
{
// this method is bound to an event somewhere

// call the parent class method, I don't care what type the parent
class is just that is has the MyCustomMethod( ) method.

if (this.Parent.Ge tType().GetMemb er("MyCustomMet hod").GetLength (0) > 0)
this.parent.MyC ustomMethod(thi s)
}

}
thanks for all the help

Nov 29 '05 #6
Another solution - what about events? Especially in the UserControl world,
this would seem to be a fairly "natural" way for a child control to indicate
something to it's parent, without the child having to know anything about a:
the parent, or b: the implementation. .. so if your child had a simple public
event, the container can subscribe and provide it's own implementation
(based on the event args), and all the child has to do is call the event?

Marc

"Gene Vital" <no********@msn ew.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..

Hi all,

I need some help in understanding how to use Generics. I have a class
based on a user control that can be put on any Container at runtime, I
want to be able to call a method on the parent class without knowing the
type of the parent class, can this be done with C#?

I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.


An example would be

public class MyClass : UserControl
{

public void SomethingChange d()
{
// this method is bound to an event somewhere

// call the parent class method, I don't care what type the parent class
is just that is has the MyCustomMethod( ) method.

if (this.Parent.Ge tType().GetMemb er("MyCustomMet hod").GetLength (0) > 0)
this.parent.MyC ustomMethod(thi s)
}

}
thanks for all the help

Nov 29 '05 #7
You bring up a good point, Marc. Objects should generally "mind their own
business." This means that a child object should generally not be calling
methods in a container. Raising an event is an excellent idea. that way, the
container can handle (or not) the event itself.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
If you push something hard enough,
it will fall over.
- Fudd's First Law of Opposition

"Marc Gravell" <mg******@rm.co m> wrote in message
news:eK******** *****@TK2MSFTNG P15.phx.gbl...
Another solution - what about events? Especially in the UserControl world,
this would seem to be a fairly "natural" way for a child control to
indicate something to it's parent, without the child having to know
anything about a: the parent, or b: the implementation. .. so if your child
had a simple public event, the container can subscribe and provide it's
own implementation (based on the event args), and all the child has to do
is call the event?

Marc

"Gene Vital" <no********@msn ew.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..

Hi all,

I need some help in understanding how to use Generics. I have a class
based on a user control that can be put on any Container at runtime, I
want to be able to call a method on the parent class without knowing the
type of the parent class, can this be done with C#?

I thought this was what Generics was supposed to be all about but I have
spent the whole day Googling and I can't find a way to do this in C#.


An example would be

public class MyClass : UserControl
{

public void SomethingChange d()
{
// this method is bound to an event somewhere

// call the parent class method, I don't care what type the parent class
is just that is has the MyCustomMethod( ) method.

if (this.Parent.Ge tType().GetMemb er("MyCustomMet hod").GetLength (0) > 0)
this.parent.MyC ustomMethod(thi s)
}

}
thanks for all the help


Nov 29 '05 #8

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

Similar topics

27
2462
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and still no can do... Any info would be great!
2
3104
by: Mr.Tickle | last post by:
So whats the deal here regarding Generics in the 2004 release and templates currently in C++?
23
2551
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
12
2744
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as it defines the language more completely. Great to use.
5
2921
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have an "AppleBasket" which is a class that contains a collection of apples. So, some code: class Fruit{ }
11
2501
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes provide an implemation of the operator +. Now I want to write another generic class Plan<DType>, which can
9
5986
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
1
2438
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
7
3257
by: SpotNet | last post by:
Hello NewsGroup, Reading up on Generics in the .NET Framework 2.0 using C# 2005 (SP1), I have a question on the application of Generics. Knowingly, Generic classes are contained in the System.Collections.Generic namespace. Literature I have read on this ties generics in with collections, hence articulate their examples as such. That's fine, I understand what is being said. My question is more towards the application and implementation...
13
3837
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
0
9579
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9979
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8861
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7393
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5433
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3948
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3551
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.