Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a static property of a generic class?

Tags:

.net

generics

I use a Height for all the Foos members. Like this

public class Foo<T> 
{
    public static int FoosHeight;
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Foo<???>.FoosHeight = 50; // DO I Set "object" here?
    }
}

The same situation is in VB.NET.

like image 409
serhio Avatar asked Feb 24 '10 14:02

serhio


People also ask

Can generic class have static method?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

Can a static class have a property?

A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.) in a static class. You can have a static constructor in a static class but you cannot have an instance constructor inside a static class.

Can properties be static in C#?

In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object. C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.

Can generic classes be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!


2 Answers

You'd have to put some generic type parameter in there. That being said, I'll sometimes use some kind of inheritance scheme to get this functionality without having to put in the generic type parameter.

public class Foo
{
    public static int FoosHeight;
}

public class Foo<T> : Foo
{
   // whatever
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Foo.FoosHeight = 50; // DO I Set "object" here?
    }
}

That being said, this will keep the same FoosHeight regardless of the generic type parameter passed into Foo<T>. If you want a different value for each version of Foo<T>, you'll have to pick a type to put in that type parameter, and forget the inheritance scheme.

like image 139
David Morton Avatar answered Sep 28 '22 04:09

David Morton


You need to specify a type, such as

Foo<int>.FoosHeight = 50;

or

Foo<Bar>.FoosHeight = 50;

but each is separate. Foo<int>.FoosHeight is not related to Foo<Bar>.FoosHeight. They're effectively two separate classes with two distinct static fields. If you want the value to be the same for all Foo<> then you need a separate place to store it like

FooHelper.FoosHeight = 50;

And FooHelper has no formal relationship with Foo<>.

like image 26
Samuel Neff Avatar answered Sep 28 '22 04:09

Samuel Neff