C# using Genetics

  • Thread starter Thread starter yootaeho
  • Start date Start date
Y

yootaeho

Hi,

I have an Object which has a list of list of objects.
For instance,

public class myClass
{
public List<FirstClass> myFirstClass {get;set;}
public List<SecondClass> mySecondClass {get;set;}
}

And both FirstClass and SecondClass have Id and Title properties.

Now I would like to create a function that takes a genetic list type
and then inside the function I would like to access Id and Title value

So something like this

public void myFunction (genetic variable)
{
// here I would like to access variable's Id and Title
}


myFunction(myClass.myFirstClass);
myFunction(myClass.mySecondClass);

Would you be able to help me to write the function me?

Thanks in advance,

Taeho
 
Do they both inherit/implement a common class or interface with those  
properties?

If not, you'll have to wait for the release of C# 4.0, which includes a  
new "dynamic" type allowing for late-binding of class members.

If they do inherit/implement a common class or interface, then you can do 
what you want with generics as they are now (by the way, note that it's  
"generic" not "genetic").  Specifically, let's assume that they both  
implement an interface that looks like this:

     interface ICommon
     {
         int Id { get; set; }
         string Title { get; set; }
     }

And the class declarations look something like this:

     class FirstClass : ICommon { ... }
     class SecondClass : ICommon { ... }

Then, you can write the desired method like this:

     void myFunction<T>(List<T> variable) where T : ICommon
     {
     }

A method like that can take as an argument any List<T> where the T  
implements ICommon.  So a List<FirstClass> or a List<SecondClass> wouldbe  
valid.

Pete

Thank you very much for your help!!!
 
Back
Top