|
| Generics with where clause. |
 |
Mon, 31 Mar 2008 12:08:57 +000 |
classC<T> where T: Counter,new()
{ // some implemention..
}
class Counter
{
// some implemention..
}
// The above coding is okay, we are restricing for only one type.
How ever my question is Generics means we can pass different parameters but
with above instance its restricted only to one type of class. Why i cannot pass
one more class in the above code itself (Generics).
Like this..
classC<T> where T: Counter,new() where T: Counter1,new() // why i cannot i
have different classes in where clause.. why it is restricted like this?
{ // some implemention..
}
class Counter
{
// some implemention..
}
class Counter1
{
// some implemention..
}
Thanks,
Vishwanath
|
| Post Reply
|
| Re: Generics with where clause. |
 |
Mon, 31 Mar 2008 12:35:51 +000 |
vishwanatha:classC<T> where T: Counter,new() where T: Counter1,new()
Where T inherits Counter and Counter1? Thats multiple inheritance which c#
doesnt support!
EDIT: If you thinking of a class that Inherits Counter or Counter1 the this is
also invalid!
Say Counter has a method MyMethod and Counter1 has no methods
How can we use T.MyMethod if the classed inherited from is counter1??
|
| Post Reply
|
| Re: Generics with where clause. |
 |
Mon, 31 Mar 2008 12:49:24 +000 |
Hi DavidKiff,
Then what is the point in having Generics. Generics means we can pass
different parameters write. so how we can apply in the above scenario with where
clause. I am waiting for the reply
Thanks,
Vishwanath
|
| Post Reply
|
| Re: Generics with where clause. |
 |
Mon, 31 Mar 2008 12:52:19 +000 |
Have both your counters implement the same interface then use that common
interface? Thats just on of many ways. Its just not possible to say if this
type or this type .. and doesnt make sense!
|
| Post Reply
|
| Re: Generics with where clause. |
 |
Tue, 1 Apr 2008 13:05:50 +0000 |
I go with David's solution. Have your generic use an interface type and both
classes implement that interface. This way, you can use your generic with
multiple classes, as long as they have the same interface.
Not that in your generic, you can only use methods of the interface that is
implemented by both classes.
class C where T: ICounter,new()
{
}
class Counter :ICounter
{
// interface implementation
}
class Counter1: ICounter
{
// interface implementation
}
C <Counter> c1 = new C<Counter>();
C <Counter1> c2 = new C<Counter1>();
|
| Post Reply
|
|
|
|
|
|
|
|
|
|