Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public class base{ public string f1; }

public class Derive1{  }

public class Derive2{  }

void fun1<T>() where T: base
{
   T t = new T();
   string f = t.f1;
}


above code works well.
let change the f1 to a static field.

What I have tried:

C#
public class base{ public static string f1; }

public class Derive1{  }

public class Derive2{  }

void fun1<T>() where T: base
{   
   string f = T.f1;  // complie error
}


How to make this code works with the static field?
Posted
Updated 12-Sep-18 9:53am
v3

Why doesn't this code (my altered example below) work? I just tried it in Linqpad (LINQPad - The .NET Programmer's Playground[^]);

C#
void Main()
{
	main m = new main();
	main.f1 = "super";
	fun1<main>();

        Derive1 d = new Derive1();
	fun1<Derive1>();
}
public class main{ static  public string f1; }

public class Derive1: main{  }

public class Derive2 : main{  }

void fun1<T>() where T: main
{   
   string f = main.f1;  // NO compile error
   Console.WriteLine(f);
}


The output will be :
super
super

which is the value of the static variable. You cannot access the static the way you were doing it. It is a CLASS variable not an instance variable. Your way was accessing the instance var.

Edit
Altered code and added Derive1 instance and ran method with that class and it works too.
Now it outputs the value (super) twice.
 
Share this answer
 
v5
You can't, not without reflection - generics do not support anything static. This shows how to use reflection to do it, if you really must. Slow though: C# accessing a static property of type T in a generic class - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900