473,765 Members | 2,012 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics and static members

Hi,

I've encountered a rather interesting language problem. Suppose I've
got following types:

//class providing usefull static methods
public class GoodBase<T>
{
public static void Met(){};
}

public class SomeEntity
: GoodBase<SomeEn tity>
{
}

public interface IDictModel<T>
where T : GoodBase<T>
{
}

public class DictModel<T>
: IDictModel<T>
where T : GoodBase<T>
{
public void Test()
{
GoodBase<SomeEn tity>.Met(); //OK
SomeEntity.Met( ); //OK
T.Met(); //won't compile
}
}

The question is why can't I call a static method using generic
parameter?

I've specified that T is of type GoodBase<T>, so static methods from
GoodBase should be available by using generic parameter... Isn't
GoodBase<SomeEn tity>.Met() actually the same as T.Met()? Why do I have
to repeat myself?

Regards,
Filip Zawada
Sep 19 '08 #1
3 1726
On Fri, 19 Sep 2008 09:27:25 -0700, Filip Zawada <fz*****@gmail. comwrote:
[...]
The question is why can't I call a static method using generic
parameter?

I've specified that T is of type GoodBase<T>, so static methods from
GoodBase should be available by using generic parameter... Isn't
GoodBase<SomeEn tity>.Met() actually the same as T.Met()? Why do I have
to repeat myself?
You don't. But, you also can't use T directly as the type.

It doesn't make sense to call static members on the type parameter. This
is true regardless of whether or not the type parameter inherits a generic
type or a non-generic one. Consider:

class A
{
public static void MethodA() { }
}

class B<T: where T : A
{
public void MethodB()
{
T.MethodA();
}
}

One of two possible behaviors may be expected here.

First, it may be expected that if the class T reimplements MethodA(), you
want the implementation in the most-derived class to be called. That is,
if T is not A and has its own implementation of MethodA, you want _that_
implementation to be called rather than A.MethodA.

If this is the case, then it's not possible for the compiler to fulfill
your intent, because it needs to know when it compiles the _generic_ class
how to get at the method, and at that point the type parameter hasn't
actually been resolved yet.

I suppose in theory, the compiler could generate some complex code to use
reflection to determine at run-time the correct static method to call.
But that could lead to a serious, non-obvious performance problem at best,
and at worst could cause some subtle, hard-to-find bugs. It's wise for
the language design to prohibit the use of a type parameter in that
context.

Of course, there's nothing stopping you from writing such code
explicitly. But in that case, it would be obvious looking at the code
that's what you're doing.

Alternatively, maybe you always want to call A.MethodA. If that's the
intent of the code, then you can get it to work by doing exactly that:

class B<T: where T : A
{
public void MethodB()
{
A.MethodA();
}
}

Note that if T inherits a generic type, then you can use the same
technique, supplying the type parameter:

class A<T>
{
public static void MethodA() { }
}

class B<T: where T : A<T>
{
public void MethodB()
{
A<T>.MethodA() ;
}
}

In your own example, it would look like this:

public class DictModel<T>
: IDictModel<T>
where T : GoodBase<T>
{
public void Test()
{
GoodBase<SomeEn tity>.Met(); //OK
SomeEntity.Met( ); //OK
GoodBase<T>.Met (); //OK
}
}

That ensures that if the Met() method depends on the type parameter, that
you actually get the implementation you desire (as opposed to calling
GoodBase<SomeEn tity>() in a class where you don't actually know that the
type parameter T is "SomeEntity ", which would be wrong).

Hope that helps.

Pete
Sep 19 '08 #2
On Fri, 19 Sep 2008 09:27:25 -0700, Filip Zawada <fz*****@gmail. comwrote:
[...]
The question is why can't I call a static method using generic
parameter?
By the way, I found these entries on Eric Lippert's blog:

http://blogs.msdn.com/ericlippert/ar...-part-one.aspx
http://blogs.msdn.com/ericlippert/ar...-part-two.aspx
http://blogs.msdn.com/ericlippert/ar...art-three.aspx

I haven't had a chance to read through them yet, but given Lippert's place
in the .NET/C# world, I would expect that these articles do a _much_
better job of explaining the issue than my short post ever could.

Pete
Sep 19 '08 #3
Thank you for the answer, Pete. It was very helpful.
Now as I know the reasons, it's so obvious.

Filip
Sep 28 '08 #4

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

Similar topics

17
3328
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 impossible to write truly generic code. For example, it seems to be impossible to write a truly generic
16
1841
by: bigtexan | last post by:
I would like to do the following and cannot figure it out. public class A<T> { public delegate T GetValueDelegate(A<T> var); public GetValueDelegate GetValue = new GetValueDelegate(B.GetValue); } public class B {
1
1649
by: Ole Nielsby | last post by:
I'm puzzled at how static fields intersect with generics, as the following snippet illustrates. namespace MonkeyParty { abstract class Fruit { } class Apple : Fruit { } class Pear : Fruit { }
11
2501
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes provide an implemation of the operator +. Now I want to write another generic class Plan<DType>, which can
1
2438
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
4
2818
by: Cedric Rogers | last post by:
I wasn't sure if I could do this. I believe I am stretching the capability of what generics can do for me but here goes. I have a generic delegate defined as public delegate bool RuleDelegate<T>(T item); In my class my goal is to use a generic list collection to contain my generic delegates. This will allow me to pass this List to another library and call this list of functions. This could provide a new way to build rule base...
8
2554
by: Gary Brown | last post by:
Hi, When I do the following public class IAmAGeneric<T> { ... public T AMember (T a, T b) { return a + b; }; }
7
3257
by: SpotNet | last post by:
Hello NewsGroup, Reading up on Generics in the .NET Framework 2.0 using C# 2005 (SP1), I have a question on the application of Generics. Knowingly, Generic classes are contained in the System.Collections.Generic namespace. Literature I have read on this ties generics in with collections, hence articulate their examples as such. That's fine, I understand what is being said. My question is more towards the application and implementation...
4
1265
by: CSharper | last post by:
I have a sample as shown in the bottom on the mail. I am trying to see without changing anything in the way the As and Bs handled. I want to make it DRY using generics. I am really interested in the AddCollection method, I see the code repeatation just because the collection is different type. Any thoughts? Thanks, using System; using System.Collections.Generic;
0
9568
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9399
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10161
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
9833
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
8831
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...
0
5275
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...
1
3924
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
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.