473,800 Members | 2,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic type with parametherized constructor

I need to create instance of generic type when generic type does not
have parameterless constructor.

I tried code below but got error shown in comment.
How to fix ?

Andrus.

abstract class QueryFactory<TE ntity{
public string O1;
public QueryFactory(st ring o1) {
O1 = o1;
}
}

class CustomerQueryFa ctory : QueryFactory<Cu stomer{
public CustomerQueryFa ctory(string o1) : base(o1) { }
}

class DocumentForm<TE ntity, TQueryFactory>
where TQueryFactory : QueryFactory<TE ntity{

public DocumentForm() {
// Cannot create an instance of the variable type 'TQueryFactory'
// because it does not have the new() constraint
var x = new TQueryFactory(" special parameter created in this method");
}
}

class Customer {
string Id { get; set; }
string Name { get; set; }
}

class Test {

static void Main() {
var x = new DocumentForm<Cu stomer, CustomerQueryFa ctory>();
}
}

Jun 27 '08 #1
9 2559
On Mon, 21 Apr 2008 01:32:15 +0300, "Andrus" <ko********@hot .ee>
wrote:
>I need to create instance of generic type when generic type does not
have parameterless constructor.

I tried code below but got error shown in comment.
How to fix ?
This article suggests an alternate solution:

http://www.codeproject.com/KB/books/EssentialCS20.aspx

(Search for "Listing 11.31" to locate the spot I'm referring to)

Regards,
Gilles.

Jun 27 '08 #2
The underlying problem is "'TQueryFactory ': cannot provide arguments when
creating an instance of a variable type"

So....

Replace:
var x = new TQueryFactory(" special parameter created in this method");

With: (btw - I did it in 2005 so couldn't test with 'var')
TQueryFactory x = (TQueryFactory) typeof(TQueryFa ctory).GetConst ructor(new
System.Type[] { typeof(string) }).Invoke(new object[] { "special parameter
created in this method" });
Hope that is what you are looking for. Apologies if I have it all wrong,
it's time to go home and I'm outahere...
If there is a better way, let me know.

Cheers.

"Andrus" <ko********@hot .eewrote in message
news:OT******** ******@TK2MSFTN GP03.phx.gbl...
I need to create instance of generic type when generic type does not
have parameterless constructor.

I tried code below but got error shown in comment.
How to fix ?

Andrus.

abstract class QueryFactory<TE ntity{
public string O1;
public QueryFactory(st ring o1) {
O1 = o1;
}
}

class CustomerQueryFa ctory : QueryFactory<Cu stomer{
public CustomerQueryFa ctory(string o1) : base(o1) { }
}

class DocumentForm<TE ntity, TQueryFactory>
where TQueryFactory : QueryFactory<TE ntity{

public DocumentForm() {
// Cannot create an instance of the variable type 'TQueryFactory'
// because it does not have the new() constraint
var x = new TQueryFactory(" special parameter created in this method");
}
}

class Customer {
string Id { get; set; }
string Name { get; set; }
}

class Test {

static void Main() {
var x = new DocumentForm<Cu stomer, CustomerQueryFa ctory>();
}
}
Jun 27 '08 #3
TQueryFactory x = (TQueryFactory) typeof(TQueryFa ctory).GetConst ructor(new
System.Type[] { typeof(string) }).Invoke(new object[] { "special parameter
created in this method" });
Thay you very much. It works.
How to invoke TQueryFactory constructor in type-safe way ?
Is this C# design flaw ?

Andrus.
Jun 27 '08 #4
Andrus wrote:
>TQueryFactor y x = (TQueryFactory) typeof(TQueryFa ctory).GetConst ructor(new
System.Type[] { typeof(string) }).Invoke(new object[] { "special parameter
created in this method" });

Thay you very much. It works.
How to invoke TQueryFactory constructor in type-safe way ?
Is this C# design flaw ?

Andrus.

Well, you could say that, but then, if a generic container had a
restriction to only allow generic types that had a constructor that took
a string parameter, what exactly would you do?

You could use it with:

- something that takes the name of an employee as a parameter
- something that takes the name of a property as a parameter
- something that takes a filename as a parameter

The likely common usage you would get out of this would not be very high.

At least that's my opinion. No doubt people might have scenarios which
would make sense, but your response is "but I know I will only use this
and that type", then my response to that would be to create descendants
of your container that knew about those specifics.

--
Lasse Vågsæther Karlsen
mailto:la***@vk arlsen.no
http://presentationmode.blogspot.com/
PGP KeyID: 0xBCDEA2E3
Jun 27 '08 #5
For info, I've got some "Type" extension methods in MiscUtil that
provide compiled (i.e. faster) access to Func<...delegat es to do
precisely this...

They aren't listed on the overview page, but they are there... IIRC, it
allows you to do things like someType.Ctor(4 , "abc", 12) etc...

http://www.pobox.com/~skeet/csharp/miscutil/

Marc
Jun 27 '08 #6
For info, I've got some "Type" extension methods in MiscUtil that provide
compiled (i.e. faster) access to Func<...delegat es to do precisely
this...

They aren't listed on the overview page, but they are there... IIRC, it
allows you to do things like someType.Ctor(4 , "abc", 12) etc...

http://www.pobox.com/~skeet/csharp/miscutil/
I tried
TQueryFactory qm = typeof(TQueryFa ctory).Ctor(Dat aBase, Ko);

but got compile error

No overload for method 'Ctor' takes '2' arguments

Andrus.
Jun 27 '08 #7
First you need to get the delegate, and ideally stow it somewhere and
re-use it; I guess I could change the code to cache this internally
without any real problems...

Marc

using System;
using MiscUtil.Linq.E xtensions;
interface IFoo
{
void Test();
}

class Bar : IFoo
{
private string message;
public Bar(string message)
{
this.message = message;
}
public void Test()
{
Console.WriteLi ne(message);
}
}

class Program
{
static void Main()
{
// perhaps loaded dynamically, etc
Type type = typeof(Bar);

// find the ctor that accepts a string, and
// return the new object as an IFoo (since
// we might not know about Bar at compile-time
// in a plugin/factory/IOC/DI model, etc)
Func<string, IFooctor = type.Ctor<strin g, IFoo>();

IFoo foo = ctor("Does it work?");
foo.Test();
}
}
Jun 27 '08 #8
Marc,
First you need to get the delegate, and ideally stow it somewhere and
re-use it; I guess I could change the code to cache this internally
without any real problems...
Thank you. It works.
I'm wondering where there is no method for single-line constructor call.

Andrus.
Jun 27 '08 #9
If the Type arg was a generic type argument, it would be trivial to
implement (via a generic cache-class); as it is, I'd need some kind of
lookup (Dictionary<Typ e, ...or similar) - that is the only issue...
but you could simply take the source code and use it to make your own
implementation. ..

Marc
Jun 27 '08 #10

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

Similar topics

49
2903
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be appreciated! Thanks! Steve ----------------------------------------------------------------------
9
4045
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
9176
by: Hyun-jik Bae | last post by:
Is that not allowed to assume generic type numeric type? As far as I've tried, I got an error with the following code: public class AAA<T> { public int Foo(T a) { return a; // error: Cannot implicitly convert type 'T' to 'int' } }
7
38616
by: Andrus | last post by:
public class BusinessObjectGeneric<EntityType: BusinessObject where EntityType : BusinessEntity, new() { public BusinessObjectGeneric<EntityType() { } ..... causes error in constructor declaration:
7
1560
by: WT | last post by:
Hello, I am building a generic class that needs to instanciate an object of its template class, something like public class MyGeneric<T> { List<TmyList = new List<T>(); void addToLst(List l) {
2
3892
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 set the constraint such that MyClass
10
2964
by: fig000 | last post by:
HI, I'm new to generics. I've written a simple class to which I'm passing a generic list. I'm able to pass the list and even pass the type of the list so I can use it to traverse it. It's a generic list of business objects. I'm able to see that the type is the correct one in the debugger. However when I try to traverse the list using the type I can't compile. The same type variable I've verified as being passed
9
3154
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
2993
by: SimonDotException | last post by:
I've written an abstract base type which uses generics to provide XML serialization and deserialization methods for use by its derived types, but I'm seemingly unable to write it in a way which completely satisfies FxCop code analysis. Here is the simplest form of the base class which reproduces the problem: public abstract class XmlSerializableItem<T> { public string ToXml() { XmlSerializer xs = new XmlSerializer( this.GetType() );...
0
10505
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10275
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10033
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3764
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.