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

Why where new() doesn't allow parameters?

Ok, I realize that it doesn't really matter because it simply isn't
possible, but does anyone know the reason why the constraint on the
generic parameters for new() doesn't allow parameters?

Ie. why isn't this allowed:

public class Collection<T> where T: SomeBaseClass, new(Session)

to make sure the type has a constructor with a Session parameter?

--
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2
Nov 28 '05 #1
4 2226
> Ie. why isn't this allowed:

public class Collection<T> where T: SomeBaseClass, new(Session) The new() constraint is used to ensure that a new instance of the class can
be created, and not the signature of the generic parameter's constructor.
Se §20.8.2 of the C# 2.0 spec for more info.
to make sure the type has a constructor with a Session parameter?

You can do this by using a static constructor on your generic type. The following
example constrains the generic T parameter to have a constructor that accepts
a single string argument:
public class ConstrainedCtorExample
{
public static void Main()
{
ConstrainedClass<ClassWithStringCtor> c=new ConstrainedClass<ClassWithStringCtor>();
Console.WriteLine("ConstrainedClass<ClassWithStrin gCtor> OK");
try
{
ConstrainedClass<ClassWithoutStringCtor> c=new ConstrainedClass<ClassWithoutStringCtor>();
}
catch (Exception)
{
Console.WriteLine("ConstrainedClass<ClassWithoutSt ringCtor> OK");
}
}
}
public class ClassWithStringCtor
{
public ClassWithStringCtor(string s)
{
}
}
public class ClassWithoutStringCtor
{
public ClassWithoutStringCtor()
{
}
}
public class ConstrainedClass<T>
{
static ConstrainedClass()
{
if (typeof(T).GetConstructor(new Type[] {typeof(string)}) == null)
{
throw new Exception(string.Format("The type '{0}' does not have a constructor
accepting a string argument",typeof(T).Name));
}
}
}

Regards,
Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 28 '05 #2
Anders Norås wrote:
Ie. why isn't this allowed:

public class Collection<T> where T: SomeBaseClass, new(Session) The new() constraint is used to ensure that a new instance of the class can
be created, and not the signature of the generic parameter's constructor.


No, it ensures that there's a public *parameterless* constructor.
Se §20.8.2 of the C# 2.0 spec for more info.


I call your 20.8.2 and raise you a 20.7.1:

<quote>
If the constraint is new(), the type argument A must not be abstract
and must have a public parameterless constructor.
</quote>
to make sure the type has a constructor with a Session parameter?

You can do this by using a static constructor on your generic type. The following
example constrains the generic T parameter to have a constructor that accepts
a single string argument:


<snip>

Hmm. Not exactly pleasant though, is it?

Jon

Nov 28 '05 #3
> No, it ensures that there's a public *parameterless* constructor.
Ok. I hear ya'!
Hmm. Not exactly pleasant though, is it?

No, but it's the only way to do it. I have found a need to constrain constructor
signatures this way in real code, but I've used it on several occations to
ensure that a generic parameter is serializable. Eg:
static MyClass()
{
if (!typeof(T).IsSerializable)
{
// throw exception
}
}

Regards,
Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 28 '05 #4
> No, but it's the only way to do it. I have found a need to constrain
constructor signatures this way in real code...

That should of coure be "I have *never* found a need"... :)

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 28 '05 #5

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

Similar topics

15
by: Jordan Rastrick | last post by:
First, a disclaimer. I am a second year Maths and Computer Science undergraduate, and this is my first time ever on Usenet (I guess I'm part of the http generation). On top of that, I have been...
822
by: Turamnvia Suouriviaskimatta | last post by:
I 'm following various posting in "comp.lang.ada, comp.lang.c++ , comp.realtime, comp.software-eng" groups regarding selection of a programming language of C, C++ or Ada for safety critical...
1
by: Foxie Foxster | last post by:
i made this private sub date_afterupdate() dim huidigeDB as database dim rsklanten, rspunten as recordset set huidigedb = currentdb set reklanten=...
4
by: Robert Schuldenfrei | last post by:
Dear NG, I was about to "improve" concurrency checking with a Timestamp when I discovered that my current code is not working. After about a day of beating my head against the wall, I am...
6
by: Robert Schuldenfrei | last post by:
Dear NG, As expected, when I went to implement TIMESTAMP, I failed. With the help of Kevin Yu, I got the 2 code segments at the bottom working using a WHERE clause that checks all columns. ...
1
by: Crercio O. Silva | last post by:
We are pleased to announce the release of the new DBManager 2.3.0. This versions is not only a bug fix but it has new features which make the application more powerful. Starting in this version...
2
by: Crazy Cat | last post by:
Using Visual Basic .NET and SQL Server 2005 I attempt to add a query that is a call to a stored procedure in the DataSet Designer. The TableAdapter Query Configuration wizard finds my stored...
21
by: Dmitry Anikin | last post by:
I mean, it's very convenient when default parameters can be in any position, like def a_func(x = 2, y = 1, z): ... (that defaults must go last is really a C++ quirk which is needed for overload...
11
by: =?Utf-8?B?QWNoaWxsZXNfX19f?= | last post by:
Im finding problem with this code. When i try to display the newindow, its not responding. It does create the new window, but doesnt respond at all. Just stays blank. I'm fairly new to c#(just a...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.