473,545 Members | 2,095 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Generic with Constraint, Custom Constructor?

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 set the constraint such that MyClass
can create T objects with some custom constructors (provided that T
has such a cstr)?

Thank you very much!

Gilbert

Oct 1 '07 #1
2 3883
I don't believe there is - at least not that I've ever seen.

The obvious workaround is to constrain your classes to be "IGilbertab le",
and have that interface define whatever signature you need:

public Interface IGilbertable
{
void Initialize(List <stringendpoint s);
IGilbertable CreateInstance( List<stringendp oints);
}

--
Chris Mullins
"gilbert@gm ail" <gi************ @gmail.comwrote in message
news:11******** **************@ k79g2000hse.goo glegroups.com.. .
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 set the constraint such that MyClass
can create T objects with some custom constructors (provided that T
has such a cstr)?

Thank you very much!

Gilbert

Oct 1 '07 #2
Gilbert,

Unfortunately, no, there isn't. The default constructor constraint is
the only one.

You could use reflection in the static constructor to check the type
parameter to see if it has the constructor that you require, but this has
the side effect of not giving you a compile-time check, just a run-time
check.

If you don't need a specific constructor, rather, if you can have an
initializer method, then I would create an interface with that method, and
implement it on your classes (if you can). Either that, or create an
interface which will act as a class factory, with one method with the
parameters you need. Then, you can have implementations of that class which
will create the classes. Something like this:

interface IPersonFactory< T>
{
public T Create(string name, int age);
}

class Person
{
public string Name;
public int Age;
}

class PersonFactory : IPersonFactory< Person>
{
public Person Create(string name, int age)
{
Person retVal = new Person();
retVal.Name = name;
retVal.Age = age;

return retVal;
}
}

class PersonUtils<TFa ctory, TPersonwhere TFactory : IPersonFactory
{
}

This way, you can have a class which will construct the instances you
need, which implements a factory interface which you can use in whatever
class you were going to make generic in the first place.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"gilbert@gm ail" <gi************ @gmail.comwrote in message
news:11******** **************@ k79g2000hse.goo glegroups.com.. .
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 set the constraint such that MyClass
can create T objects with some custom constructors (provided that T
has such a cstr)?

Thank you very much!

Gilbert

Oct 1 '07 #3

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

Similar topics

1
2710
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 classes with no default constructor can not be arguments of generic types. Why I can not specify "new ( smth. )" as a constraint of a generic parameter?...
17
3295
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 way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even...
9
4031
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 T:new()
4
2038
by: Jethro Guo | last post by:
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...
5
4561
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public constructors (because we do not allow developers to instantiate them directly). Because our business objects are instantiated very frequently, the idea...
6
4633
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 unless it is nullable. Why doesn't this work? public class Metadata<T> where T: System.int line from the docs
9
12797
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 implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The...
3
1736
by: BombDrop | last post by:
I'm working on a system that has 4 different types of client they have mostly the same attributes so I decided to create an interface IClient for them to implement and then just add the differing attributes as needed to each client class. Now I get the Client information from a DB and Load them into a Generic dictionary
9
3137
by: tadmill | last post by:
Is it possible to pass a generic parameter of the same class to to its constructor, where the "T" type passed in the constructor is different than the "T" type of the instanced class? ie, public class SomeList<T> { public SomeList(SomeList<TthisSomeList)
0
7464
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...
0
7396
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7751
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5968
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...
1
5323
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...
0
4943
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...
1
1874
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
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.