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

C# Generic Constraint Improve Way (Jethro Guo)

C++ template use constraint by signature,It's very flexible to programmer but
complex for complier, and at most time programmer can not
get clear error message from complier if error occur. C# generic use
constraint by type,complier is relaxed, but it is very limited to
programmer.Is there a way to get merits of both?

Maybe the following way can achieve this purpose :

//First add a keyword "constrant" to modify class or struct just like
keyword "abstract"
//Used to define constrant, so the meta data can be treat same as common
class.
constrant class TRef : ISomeInterface
{
//Constructors
public TRef();
public TRef(int i);

//Methods
public static bool operator ==(TRef t1, TRef t2);
public static bool operator +(TRef t1, TRef t2);
public void Method1();
public void Method2(TRef t, int i);

//Properties
public int Property1{get;set;}
public int this[int i]{get;}
}

constrant struct TValue: ISomeInterface
{
//Constructors
public TValue();
public TValue(int i);

//Static Methods
public static bool operator ==(TValue t1, TValue t2);
public static bool operator +(TValue t1, TValue t2);
public void Method1();
public void Method2(TValue t, int i);

//Properties
public int Property1{get;set;}
public int this[int i]{get;}
}

//GenericClass use TRef,TValue as normal class,compiler can give clear error
message
public class GenericClass<TRef,TValue>
//Note here use constrant class or struct directly
//"where" statement is not needed now
{
public void sample()
{
//here just treat TRef,TValue as normal class

TRef refObj = new TRef();
TRef refObj2 = new TRef(1);

TRef refObj3 = refObj + refObj2;

TValue valueObj = new TValue(100);
TValue valueObj2 = new TValue(10);

if (valueObj == valueObj2)
{
valueObj.Method1();
valueObj2.Method2();
}

int i=refObj3.Property1;
int j=valueObj2[0];
}
}

public class UseGenericClass
{
public void Test()
{
//Compiler will check:
//RealClass includes all signatures of TRef, but do not force
RealClass inherited from TRef;
//RealValue includes all signatures of TValue
GenericClass<RealClass,RealValue> obj=new
GenericClass<RealClass,RealValue>();
}
}
Dec 9 '05 #1
4 2016
Jethro,

No, right now, there is no way to get a constraint on a signature. MS
intentionally decided to work slowly with the constraint system to see what
the needs would be, so that they wouldn't make an error early on.

Also, the reason C++ can use constraints by signature easier than .NET
is that templates are a compile-time feature. With .NET, it is implemented
in the runtime, so it is a much more difficult thing to do (although not
impossible).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Jethro Guo" <Je*******@discussions.microsoft.com> wrote in message
news:70**********************************@microsof t.com...
C++ template use constraint by signature,It's very flexible to programmer
but
complex for complier, and at most time programmer can not
get clear error message from complier if error occur. C# generic use
constraint by type,complier is relaxed, but it is very limited to
programmer.Is there a way to get merits of both?

Maybe the following way can achieve this purpose :

//First add a keyword "constrant" to modify class or struct just like
keyword "abstract"
//Used to define constrant, so the meta data can be treat same as common
class.
constrant class TRef : ISomeInterface
{
//Constructors
public TRef();
public TRef(int i);

//Methods
public static bool operator ==(TRef t1, TRef t2);
public static bool operator +(TRef t1, TRef t2);
public void Method1();
public void Method2(TRef t, int i);

//Properties
public int Property1{get;set;}
public int this[int i]{get;}
}

constrant struct TValue: ISomeInterface
{
//Constructors
public TValue();
public TValue(int i);

//Static Methods
public static bool operator ==(TValue t1, TValue t2);
public static bool operator +(TValue t1, TValue t2);
public void Method1();
public void Method2(TValue t, int i);

//Properties
public int Property1{get;set;}
public int this[int i]{get;}
}

//GenericClass use TRef,TValue as normal class,compiler can give clear
error
message
public class GenericClass<TRef,TValue>
//Note here use constrant class or struct directly
//"where" statement is not needed now
{
public void sample()
{
//here just treat TRef,TValue as normal class

TRef refObj = new TRef();
TRef refObj2 = new TRef(1);

TRef refObj3 = refObj + refObj2;

TValue valueObj = new TValue(100);
TValue valueObj2 = new TValue(10);

if (valueObj == valueObj2)
{
valueObj.Method1();
valueObj2.Method2();
}

int i=refObj3.Property1;
int j=valueObj2[0];
}
}

public class UseGenericClass
{
public void Test()
{
//Compiler will check:
//RealClass includes all signatures of TRef, but do not force
RealClass inherited from TRef;
//RealValue includes all signatures of TValue
GenericClass<RealClass,RealValue> obj=new
GenericClass<RealClass,RealValue>();
}
}

Dec 9 '05 #2
Your proposed syntax is interesting. I find it confusing that the
constraint class TRef is automatically matched up with the type
parameter TRef without a where clause, though. Type parameter names are
normally local to the generic class/method where they're declared - one
class's TKey might have nothing in common with another class's TKey.

I've been thinking about possible extensions too. I'm so frustrated by
the power that generics *almost* have that I might even try to hack
these into Mono's compiler to test them. Here are a couple of my
ideas...

Signature constraints:

public T Sum(params T[] items)
where T has static T operator +(T left, T right)
{
T result;
foreach (T item in items) result = result + item;
return result;
}

"has" can be a contextual keyword like "where". The constraint passes
if the type argument has an accessible method with the given signature,
which can be an instance method or static method (including operators).

Implicit interface constraints:

public interface IContainer<T>
{
void Add(T item);
void Remove(T item);
}

public void AddItemToContainer<TCont,TItem>(TCont container, TItem
item)
where TCont : implicit IContainer<TItem>
{
container.Add(item);
}

"implicit" is already a keyword, but this is a new use. The constraint
passes if the type argument implements the given interface, or if it
*could* implement the given interface (i.e. if you could add it to the
class's definition and the class would still compile). Basically, this
is shorthand so you don't have to write a signature constraint for each
method of the interface.

TCont here could be any type that has an Add(TItem) and Remove(TItem)
method. You couldn't pass "container" to a method that expected an
IContainer<TItem> parameter, since it doesn't necessarily implement the
interface for real, but you could still call the Add and Remove
methods.

One problem with this implicit interface syntax is that interfaces
can't have static methods, and IMO if static methods in an interface
were allowed, they should work like regular static methods; they
shouldn't be part of the interface contract.

Perhaps static interfaces? Something like this:

static interface IArithmetic<T>
{
static T operator +(T left, T right);
static T operator -(T left, T right);
...
}

Such an interface wouldn't be very useful outside of those implicit
interface constraints, though.

Jesse
Jethro Guo wrote:
C++ template use constraint by signature,It's very flexible to programmer but
complex for complier, and at most time programmer can not
get clear error message from complier if error occur. C# generic use
constraint by type,complier is relaxed, but it is very limited to
programmer.Is there a way to get merits of both?

Maybe the following way can achieve this purpose :

//First add a keyword "constrant" to modify class or struct just like
keyword "abstract"
//Used to define constrant, so the meta data can be treat same as common
class.
constrant class TRef : ISomeInterface
{
//Constructors
public TRef();
public TRef(int i);

//Methods
public static bool operator ==(TRef t1, TRef t2);
public static bool operator +(TRef t1, TRef t2);
public void Method1();
public void Method2(TRef t, int i);

//Properties
public int Property1{get;set;}
public int this[int i]{get;}
}

constrant struct TValue: ISomeInterface
{
//Constructors
public TValue();
public TValue(int i);

//Static Methods
public static bool operator ==(TValue t1, TValue t2);
public static bool operator +(TValue t1, TValue t2);
public void Method1();
public void Method2(TValue t, int i);

//Properties
public int Property1{get;set;}
public int this[int i]{get;}
}

//GenericClass use TRef,TValue as normal class,compiler can give clear error
message
public class GenericClass<TRef,TValue>
//Note here use constrant class or struct directly
//"where" statement is not needed now
{
public void sample()
{
//here just treat TRef,TValue as normal class

TRef refObj = new TRef();
TRef refObj2 = new TRef(1);

TRef refObj3 = refObj + refObj2;

TValue valueObj = new TValue(100);
TValue valueObj2 = new TValue(10);

if (valueObj == valueObj2)
{
valueObj.Method1();
valueObj2.Method2();
}

int i=refObj3.Property1;
int j=valueObj2[0];
}
}

public class UseGenericClass
{
public void Test()
{
//Compiler will check:
//RealClass includes all signatures of TRef, but do not force
RealClass inherited from TRef;
//RealValue includes all signatures of TValue
GenericClass<RealClass,RealValue> obj=new
GenericClass<RealClass,RealValue>();
}
}


Dec 10 '05 #3
Jesse McGrew wrote:
Your proposed syntax is interesting. I find it confusing that the
constraint class TRef is automatically matched up with the type
parameter TRef without a where clause, though. Type parameter names are
normally local to the generic class/method where they're declared - one
class's TKey might have nothing in common with another class's TKey.

I've been thinking about possible extensions too. I'm so frustrated by
the power that generics *almost* have that I might even try to hack
these into Mono's compiler to test them. Here are a couple of my
ideas...

Signature constraints:

public T Sum(params T[] items)
where T has static T operator +(T left, T right)
{
T result;
foreach (T item in items) result = result + item;
return result;
}


Other possible signature constraints:

where T has new(String session)
where T has static T Parse(String value)

the new(String) constraint would be irksome as AFAIK it would match any
constructor that takes a string, not necessarily one that is named
"session" or has the same meaning. This is clearly what interfaces are
about, documented contract, but then interfaces doesn't allow you to
construct new instances of any type of object.

I've needed the first of those two and had to hack it with the Activator
object. Doable but doesn't seem in the spirit of generics.

<snip>

--
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2
Dec 13 '05 #4
Lasse Vågsæther Karlsen wrote:
[...]
Other possible signature constraints:

where T has new(String session)
where T has static T Parse(String value)

the new(String) constraint would be irksome as AFAIK it would match any
constructor that takes a string, not necessarily one that is named
"session" or has the same meaning. This is clearly what interfaces are
about, documented contract, but then interfaces doesn't allow you to
construct new instances of any type of object.
I think I'd prefer:

where T : new(String session)

Just because it matches the existing syntax.

As far as matching a constructor that has the same meaning, you could
define an empty interface and use it to mark the classes that do what
you want:

where T : new(String session), IConstructWithSessionString
I've needed the first of those two and had to hack it with the Activator
object. Doable but doesn't seem in the spirit of generics.


You're in good company, though... even when you use the default
constructor constraint, new T() is compiled as a call to
Activator.CreateInstance<T>() anyway. All you get with the constraint
is compile-time verification that the call will succeed.

Jesse

Dec 16 '05 #5

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

Similar topics

2
by: yongsing | last post by:
I have two tables as shown below (only relevant columns shown). The second table is dependent on the first one. CREATE TABLE PARENTTABLE ( ... SERIAL CHAR(12) NOT NULL, ENDDATE TIMESTAMP NOT...
1
by: Dmitry Martynov | last post by:
What if I have some special constructors and do not have a default constructor. It seems to be very useful when I do not want to forget to initialize some fields properly. As I have understood...
17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
9
by: Alon Fliess | last post by:
Hi I am trying to write a generic class that instantiates the generic type, but I can not find the correct way to give it the constructor constraint. For example: In C#: class X<T> where...
6
by: Dan Holmes | last post by:
I have a class that i need a constraint of int, string, float or bool. I have tried the following but can't make VS accept it. I read the docs and they showed that any value type can be used...
3
by: BBM | last post by:
Hi, I have a situation where I would like to extend an abstract (MustInherit) class that uses a Generic parameter. The class declaration looks like this... Public MustInherit Class...
9
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that...
2
by: gilbert | last post by:
Hello. I am trying to use c# generic to define a class. class MyClass<Twhere T: new(){ } In this definition, MyClass can create T objects with a default constructor. Is there any way to...
4
by: Weeble | last post by:
I have an interface that looks something like this: public interface IFoo<Twhere T : IFoo<T{ ... } Inside a class that looks something like this... public class Bar<V{ ... } ....I would like to...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...

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.