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

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<TEntity{
public string O1;
public QueryFactory(string o1) {
O1 = o1;
}
}

class CustomerQueryFactory : QueryFactory<Customer{
public CustomerQueryFactory(string o1) : base(o1) { }
}

class DocumentForm<TEntity, TQueryFactory>
where TQueryFactory : QueryFactory<TEntity{

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<Customer, CustomerQueryFactory>();
}
}

Jun 27 '08 #1
9 2537
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(TQueryFactory).GetConstructo r(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**************@TK2MSFTNGP03.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<TEntity{
public string O1;
public QueryFactory(string o1) {
O1 = o1;
}
}

class CustomerQueryFactory : QueryFactory<Customer{
public CustomerQueryFactory(string o1) : base(o1) { }
}

class DocumentForm<TEntity, TQueryFactory>
where TQueryFactory : QueryFactory<TEntity{

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<Customer, CustomerQueryFactory>();
}
}
Jun 27 '08 #3
TQueryFactory x = (TQueryFactory)typeof(TQueryFactory).GetConstructo r(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:
>TQueryFactory x = (TQueryFactory)typeof(TQueryFactory).GetConstructo r(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***@vkarlsen.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<...delegates 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<...delegates 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(TQueryFactory).Ctor(DataBase, 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.Extensions;
interface IFoo
{
void Test();
}

class Bar : IFoo
{
private string message;
public Bar(string message)
{
this.message = message;
}
public void Test()
{
Console.WriteLine(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<string, 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<Type, ...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
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...
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...
4
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...
7
by: Andrus | last post by:
public class BusinessObjectGeneric<EntityType: BusinessObject where EntityType : BusinessEntity, new() { public BusinessObjectGeneric<EntityType() { } ..... causes error in constructor...
7
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...
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...
10
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...
9
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, ...
0
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...
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...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.