How can I get class information by property w/ reflection C# - c#

I have code:
// entity
public class PermissInfo
{
public int PermissValue { get; set; }
}
// used class
public class MenuPermiss
{
public static readonly PermissInfo PermissView = new PermissInfo { PermissValue = 1 };
public static readonly PermissInfo PermissEdit = new PermissInfo { PermissValue = 2 };
public static readonly PermissInfo PermissDelete = new PermissInfo { PermissValue = 4 };
}
And implement code like:
// implement class: check permiss
public static class ImplementClass
{
// used like: return CheckPermiss(MenuPermiss.PermissEdit);
public static bool CheckPermiss(PermissInfo permiss)
{
// How to get "MenuPermiss" class info by "permiss" param
return false;
}
}
How can i get MenuPermiss CLASS by MenuPermiss.PermissEdit param?

It is not possible using this syntax:
ImplementClass.DoSomething(MyClass.MyProperty);
but possible with this one:
ImplementClass.DoSomething(() => MyClass.MyProperty);
Solution:
using System.Linq.Expressions;
public static class ImplementClass
{
public static bool DoSomething<T>(Expression<Func<T>> propertyExpression)
{
var memberInfo = ((MemberExpression)propertyExpression.Body).Member;
var declaringType = memberInfo.DeclaringType;
Console.WriteLine(declaringType.Name); // outputs "MyClass"
return false;
}
}

Link reference here:
It work good with syntax:
PermissHelper.CheckPermiss(()=>MenuPermiss.PermissDelete)
I try implement with this code, and it's return "<>c__DisplayClass0" value. How to fix it?
PermissHelper.CheckPermiss(MenuPermiss.PermissDelete)
and
public static string CheckPermiss(PermissInfo permissInfo)
{
Expression<Func<PermissInfo>> x = () => permissInfo;
var memberInfo = ((MemberExpression)x.Body).Member;
var declaringType = memberInfo.DeclaringType;
return declaringType != null ? declaringType.Name : "";
}

Related

Creating an Enum of GUIDs

I used this accepted answer to create an Enum of Guids.
public enum AccessRoles
{
[EnumGuid("2ED3164-BB48-499B-86C4-A2B1114BF1")]
SysAdmin =1,
[EnumGuid("A5690E7-1111-4AFB-B44D-1DF3AD66D435")]
Admin = 2,
[EnumGuid("30558C7-66D9-4189-9BD9-2B87D11190")]
OrgAdmin = 3,
}
class EnumGuid : Attribute
{
public Guid Guid;
public EnumGuid(string guid)
{
Guid = new Guid(guid);
}
}
I try check if a Guid is part of an enum, it throws an exception System.InvalidOperationException even though userId = 2ED3164-BB48-499B-86C4-A2B1114BF1 is a valid guid.
if(Enum.IsDefined(typeof(AccessRoles), userId))
{
}
I tried converting it to string and checking, but that time it does not throw an error but does not go inside the if loop.
if(Enum.IsDefined(typeof(AccessRoles), userId.ToString().ToUpper()))
{
}
So how do I fix it? Or is there a better way? I want to avoid the multiple if statements or a case statement and so what to use it as enums so they are reusable.
I would replace your enum with an immutable struct, and add a static class to hold all possible roles in the application:
public struct AccessRole
{
public AccessRole(Guid guid, int number, string name) : this()
{
Uuid = guid;
Number = number;
Name = name;
}
public Guid Uuid {get;}
public int Number {get;}
public string Name {get;}
}
Then you can add a static class for AccessRoles:
public static class AccessRoles
{
private static List<AccessRole> _roles;
static AccessRoles()
{
_roles = new List<AccessRole>();
// Here I populate it hard coded for the sample,
// but it should be populated from your database or config file
_roles.Add(new AccessRole(new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1"), 1, "SysAdmin"));
_roles.Add(new AccessRole(new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435"), 2, "Admin"));
_roles.Add(new AccessRole(new Guid("30558C7-66D9-4189-9BD9-2B87D11190"), 3, "OrgAdmin"));
}
public static AccessRole GetRole(Guid uuid)
{
return _roles.Find(r => r.Uuid == uuid);
}
public static AccessRole GetRole(int number)
{
return _roles.Find(r => r.Number == number);
}
public static AccessRole GetRole(string name)
{
return _roles.Find(r => r.Name == name);
}
}
Now all you have to do is change the way the _roles list is populated in the static constructor to either a database of a configuration file, and you're good to go.
Note that the AccessRoles provides static methods to get a search for a role by either property. It can be replaced with a single method that will get a predicate, but I think that this way it's more readable.
I would suggest a complete different approach, when working with fixed user roles.
Using an Enumeration you can achieve same and much more:
public abstract class UserRoleType : Enumeration<UserRoleType>
{
protected UserRoleType(int value, string displayName)
: base(value, displayName)
{}
public static readonly UserRoleType Unknown = new UnknownRoleType();
public static readonly UserRoleType Administrator = new AdministratorRoleType();
public static readonly UserRoleType System = new SystemRoleType();
public static readonly UserRoleType Moderator = new ModeratorRoleType();
public virtual bool CanCreateUser => false;
public virtual bool CanBlockUser => false;
public virtual bool CanResetUserPassword => false;
}
public sealed class UnknownRoleType : UserRoleType
{
public UnknownRoleType()
: base(0, "Unknown")
{ }
}
public sealed class AdministratorRoleType : UserRoleType
{
public AdministratorRoleType()
: base(10, "Administrator")
{}
public override bool CanCreateUser => true;
public override bool CanBlockUser => true;
public override bool CanResetUserPassword => true;
}
public sealed class SystemRoleType : UserRoleType
{
public SystemRoleType()
: base(20, "System")
{ }
public override bool CanBlockUser => true;
public override bool CanResetUserPassword => true;
}
public sealed class ModeratorRoleType : UserRoleType
{
public ModeratorRoleType()
: base(40, "Moderator")
{ }
public override bool CanBlockUser => true;
}
By setting abstract/virtual properties on the abstract UserRoleType, you system only have operate on the abstract class.
When your user context is being initialized (on login), you simply find the user role by
var roleTypeValueFromDatabase = 10;
var roleType = UserRoleType.FromValueOrDefault(roleTypeValueFromDatabase, UserRoleType.Unknown);
if (roleType.CanCreateUser)
{
// create user..
}
// Find roles with specific rights
var rolesThatCanResetPassword = UserRoleType.GetAll().Where(urt => urt.CanResetUserPassword);
About the Enumeration class, there are several implementation of them on github/nuget.
Mine is for .Net core v2 - https://github.com/microknights/Collections
with Nuget: Install-Package MicroKnights.Collections
Headspring - https://github.com/HeadspringLabs/Enumeration
source files only.
public enum AccessRoles
{
SysAdmin = 1,
Admin = 2,
OrgAdmin = 3
}
public class Attributes
{
public static Dictionary<int, Guid> Attribute = new Dictionary<int, Guid>()
{
{(int)AccessRoles.SysAdmin, Guid.Parse("6D18698C-04EC-4E50-84DB-BE513D5875AC")},
{(int)AccessRoles.Admin, Guid.Parse("32E86718-7034-4640-9076-A60B9B6CA51A")},
{(int)AccessRoles.OrgAdmin, Guid.Parse("2CA39E37-8AEA-463F-AE14-E9D92AC5FB5E")}
};
}
Console.WriteLine(Attributes.Attribute[(int)AccessRoles.SysAdmin]);
Console.WriteLine(Attributes.Attribute[(int)AccessRoles.Admin]);
Console.WriteLine(Attributes.Attribute[(int)AccessRoles.OrgAdmin]);
Maybe passing the Guid values with System.ComponentModel.AmbientValueAttribute like so :
using System.ComponentModel;
public enum AccessRoles
{
[AmbientValue(typeof(Guid), "749e73c0-ba25-4f69-9f81-ec21d9942e52")]
SysAdmin = 1,
[AmbientValue(typeof(Guid), "39cc7e3d-db5f-4619-a577-e24cb89de5a7")]
Admin = 2,
[AmbientValue(typeof(Guid), "93902f8d-46d3-4b43-b684-b0ee66bbf7de")]
OrgAdmin = 3,
}
With an extension to obtain the AmbientValue:
using System.Reflection;
public static class EnumExtensions
{
public static object GetAmbientValue(this Enum enumVal)
{
Type type = enumVal.GetType();
MemberInfo[] memInfo = type.GetMember(enumVal.ToString());
object[] attributes = memInfo[0].GetCustomAttributes(typeof(AmbientValueAttribute), false);
if (attributes == null || attributes.Length == 0)
return default;
return ((AmbientValueAttribute)attributes[0]).Value;
}
}
And finally obtaining the Guid value like so :
var valGuid = (Guid)AccessRoles.SysAdmin.GetAmbientValue();

Is there a way for me to access a C# class attribute?

Is there a way for me to access a C# class attribute?
For instance, if I have the following class:
...
[TableName("my_table_name")]
public class MyClass
{
...
}
Can I do something like:
MyClass.Attribute.TableName => my_table_name
Thanks!
You can use Attribute.GetCustomAttribute method for that:
var tableNameAttribute = (TableNameAttribute)Attribute.GetCustomAttribute(
typeof(MyClass), typeof(TableNameAttribute), true);
However this is too verbose for my taste, and you can really make your life much easier by the following little extension method:
public static class AttributeUtils
{
public static TAttribute GetAttribute<TAttribute>(this Type type, bool inherit = true) where TAttribute : Attribute
{
return (TAttribute)Attribute.GetCustomAttribute(type, typeof(TAttribute), inherit);
}
}
so you can use simply
var tableNameAttribute = typeof(MyClass).GetAttribute<TableNameAttribute>();
You can use reflection to get it. Here's is a complete encompassing example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class TableNameAttribute : Attribute
{
public TableNameAttribute(string tableName)
{
this.TableName = tableName;
}
public string TableName { get; set; }
}
[TableName("my_table_name")]
public class SomePoco
{
public string FirstName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var classInstance = new SomePoco() { FirstName = "Bob" };
var tableNameAttribute = classInstance.GetType().GetCustomAttributes(true).Where(a => a.GetType() == typeof(TableNameAttribute)).Select(a =>
{
return a as TableNameAttribute;
}).FirstOrDefault();
Console.WriteLine(tableNameAttribute != null ? tableNameAttribute.TableName : "null");
Console.ReadKey(true);
}
}
}
Here's an extension that will make it easier, by extending object to give you an attribute helper.
namespace System
{
public static class ReflectionExtensions
{
public static T GetAttribute<T>(this object classInstance) where T : class
{
return ReflectionExtensions.GetAttribute<T>(classInstance, true);
}
public static T GetAttribute<T>(this object classInstance, bool includeInheritedAttributes) where T : class
{
if (classInstance == null)
return null;
Type t = classInstance.GetType();
object attr = t.GetCustomAttributes(includeInheritedAttributes).Where(a => a.GetType() == typeof(T)).FirstOrDefault();
return attr as T;
}
}
}
This would turn my previous answer into:
class Program
{
static void Main(string[] args)
{
var classInstance = new SomePoco() { FirstName = "Bob" };
var tableNameAttribute = classInstance.GetAttribute<TableNameAttribute>();
Console.WriteLine(tableNameAttribute != null ? tableNameAttribute.TableName : "null");
Console.ReadKey(true);
}
}

How to get a default generic delegate for a type

I have a generic delegate like this:
public delegate T SomeHandler<T>(T input);
I have a generic class that take the delegate as a parameter to its constructor like this:
public class SomeClass<T>
{
private SomeHandler<T> m_handler;
public SomeClass(SomeHandler<T> handler)
{
m_handler = handler;
}
public void DoSomeStuff(T input)
{
T result = m_handler(input);
// some stuff
}
}
Most of the time I would instantiate the class with a default handler unless some special case is needed. So I have some default handlers for the types I use:
public static class DefaultHandlers
{
public static string DefaultStringHandler(string input)
{
return input;
}
}
In some cases, the type is instantiated with a special handler that is specific to its implementation:
public class Example
{
private SomeClass<string> m_typicalCase;
private SomeClass<string> m_specialCase;
public Example()
{
m_typicalCase = new SomeClass<string>(DefaultHandlers.DefaultStringHandler);
m_specialCase = new SomeClass<string>(SpecialHandler);
}
private string SpecialHandler(string input)
{
string result;
// Do something special
return result;
}
}
I want to create a default constructor for SomeClass that always instantiates the class with the same default handler for that type, but since the type is not know at compile time, I can't return the delegate that is the right type.
public class SomeClass<T>
{
...
public SomeClass()
{
m_handler = DefaultHandlers.GetDefaultHandler<T>();
}
...
}
Like this
public static class DefaultHandlers
{
public static SomeHandler<T> GetDefaultHandler<T>()
{
if (typeof(T) == typeof(string))
{
return DefaultStringHandler;
}
}
}
This does not work becuase DefaultStringHandler returns a string and the method expects T.
The only way that I have found to do this is the make a type-specific subclass of SomeClass that overloads the default constructor:
public class SomeStringClass : SomeClass<string>
{
public SomeStringClass()
: base(DefaultHandlers.DefaultStringHandler)
{
}
public SomeStringClass(SomeHandler<string> handler)
: base(handler)
{
}
}
It would be fun if generic types could have type-specific overloaded constructors that are used when instantiating the class of a specific type:
public class Foo<T>
{
public Foo<string>(string input)
{
}
public Foo<int>(int input)
{
}
public Foo(T input)
{
}
}
There must be a more elegant way to do with with a design pattern, Strategy maybe?
You could utilize dynamic to get something like SomeClass<string>():
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Zoltan
{
public class SomeClass<T>
{
private static readonly Func<T,T> FALL_BACK_HANDLER = a => a; //or what have you
private readonly Func<T,T> m_handler;
public SomeClass(Func<T,T> handler)
{
m_handler = handler;
}
public SomeClass()
{
m_handler = DefaultHandler.For<T>() ?? FALL_BACK_HANDLER;
}
public void DoSomeStuff(T input)
{
T result = m_handler(input);
Console.WriteLine(result);
}
}
public static class DefaultHandler
{
public static Func<T,T> For<T>()
{
return TypeAware<T>.Default;
}
private static class TypeAware<T>
{
private static readonly Func<T,T> DEFAULT;
static TypeAware()
{
var type = typeof(T);
if (type == typeof(string))
{
DEFAULT = a => DefaultHandler.StringHandler((dynamic) a);
}
else if (type == typeof(int))
{
DEFAULT = a => DefaultHandler.IntHandler((dynamic) a);
}
else
{
DEFAULT = null;
}
}
public static Func<T,T> Default { get { return DEFAULT; } }
}
public static string StringHandler(string a)
{
return a + " The default handler does some stuff!";
}
public static int IntHandler(int a)
{
return a + 2;
}
}
}
You would then consume SomeClass as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Zoltan
{
public class Program
{
public static void Main(string[] args)
{
var someStringObj = new SomeClass<string>();
someStringObj.DoSomeStuff("Hello World.");//prints "Hello World. The default handler does some stuff!"
var someIntObj = new SomeClass<int>();
someIntObj.DoSomeStuff(1);//prints 3
var someCustomDoubleObj = new SomeClass<double>(d => d - 2);
someCustomDoubleObj.DoSomeStuff(3);//prints 1
Console.Read();
}
}
}
Building on Jon Skeet and Alexei Levenkovs comments. From what I understand, something like this might be what you're after?
public delegate T SomeHandler<T>(T input);
public class SomeClass<T>
{
private SomeHandler<T> m_handler;
public SomeClass()
{
m_handler = (T input) => input;
}
public SomeClass(SomeHandler<T> handler)
{
m_handler = handler;
}
public void DoSomeStuff(T input)
{
T result = m_handler(input);
// some stuff
}
}
Another way would be to move the string-specific behaviour into a separate class and simply make an instance of that class if you want specific behaviour tied to a specific type
public delegate T SomeHandler<T>(T input);
public class SomeClass<T>
{
protected SomeHandler<T> m_handler;
protected SomeClass()
{
}
public SomeClass(SomeHandler<T> handler)
{
m_handler = handler;
}
public void DoSomeStuff(T input)
{
T result = m_handler(input);
// some stuff
}
}
public class SomeStringClass : SomeClass<string>
{
public SomeStringClass()
{
m_handler = DefaultStringHandler;
}
private string DefaultStringHandler(string input)
{
// Do default string stuff here...
return input;
}
public SomeStringClass(SomeHandler<string> handler):base(handler)
{
}
}

Why is FieldInfo.GetValue(null) not working in static constructor

See the code below. I want a class that automatically enumerates all the defined static readonly instances of its own type (see TestClass as an example, it defines 3 static readonly instances of its own type).
I want this automation because I want to loop over the defined types and not risk the change of forgetting to add a new instance to the list of All.
Ok, I have it working, that is not the point. But why doesn't FillAll work when called from a static constructor? See the commented static constructor in DefinedInstancesBase<T> code. I mean FieldInfo.GetValue(null) returns null in the static constructor, though the debugger has already hit creating the static readonly instances before the FieldInfo.GetValue(null) is called.
I'm very curious why it doesn't work. Is this by design?
public abstract class DefinedInstancesBase<T>
{
public static IList<T> All
{
get
{
if (_All == null)
{
FillAll();
}
return _All;
}
}
//Why this doesn't work? No idea.
//static DefinedInstancesBase()
//{
// FillAll();
//}
private static void FillAll()
{
var typeOfT = typeof(T);
var fields = typeOfT.GetFields(BindingFlags.Public | BindingFlags.Static);
var fieldsOfTypeT = fields.Where(f => f.FieldType == typeOfT);
_All = new List<T>();
foreach (var fieldOfTypeT in fieldsOfTypeT)
{
_All.Add((T)fieldOfTypeT.GetValue(null));
}
}
private static List<T> _All = null;
}
[TestClass]
public class DefinedInstancesTest
{
[TestMethod]
public void StaticReadOnlyInstancesAreEnumerated()
{
//Given
var expectedClasses = new List<TestClass>
{
TestClass.First,
TestClass.Second,
TestClass.Third,
};
//When
var actualClasses = TestClass.All;
//Then
for (var i=0; i<expectedClasses.Count; i++)
{
Assert.AreEqual(expectedClasses[i].Id, actualClasses[i].Id);
}
}
private class TestClass : DefinedInstancesBase<TestClass>
{
public static readonly TestClass First = new TestClass(1);
public static readonly TestClass Second = new TestClass(2);
public static readonly TestClass Third = new TestClass(3);
public int Id { get; private set; }
private TestClass(int pId)
{
Id = pId;
}
}
}
There are two separate issues at work here.
There is a typo in your static constructor in the code above. Try changing static DefinedInstances() to static DefinedInstancesBase(), because currently it is just specified as a private static function.
The second and more important issue is to understand the order that the various constructors are being called in. What is happening is that the static constructor on the base abstract class is getting triggered by the instantiation (during member initializer) of the First field in the derived class. Therefore, First is still null when the static constructor of DefinedInstancesBase class is being called (and thus the FindAll() method).
See the following code (slightly modified to better illustrate the issue) and output:
public void Main()
{
DefinedInstancesTest dit = new DefinedInstancesTest();
dit.StaticReadOnlyInstancesAreEnumerated();
}
public abstract class DefinedInstancesBase<T>
{
public static IList<T> All
{
get
{
//if (_All == null)
// FillAll();
return _All;
}
}
// correctly named static ctor
static DefinedInstancesBase() { FillAll(); }
private static void FillAll()
{
Console.WriteLine("FillAll() called...");
var typeOfT = typeof(T);
var fields = typeOfT.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var fieldsOfTypeT = fields.Where(f => f.FieldType == typeOfT);
_All = new List<T>();
foreach (var fieldOfTypeT in fieldsOfTypeT)
{
_All.Add((T)fieldOfTypeT.GetValue(null));
}
}
private static List<T> _All = null;
}
//[TestClass]
public class DefinedInstancesTest
{
//[TestMethod]
public void StaticReadOnlyInstancesAreEnumerated()
{
//Given
var expectedClasses = new List<TestClass>
{
TestClass.First,
TestClass.Second,
TestClass.Third,
};
//When
var actualClasses = TestClass.All;
//Then
for (var i=0; i<expectedClasses.Count; i++)
{
//Assert.AreEqual(expectedClasses[i].Id, actualClasses[i].Id);
if (expectedClasses[i].Id != actualClasses[i].Id)
Console.WriteLine("not equal!");
}
}
private class TestClass : DefinedInstancesBase<TestClass>
{
public static readonly TestClass First;
public static readonly TestClass Second;
public static readonly TestClass Third;
public int Id { get; private set; }
static TestClass()
{
Console.WriteLine("TestClass() static ctor called...");
First = new TestClass(1);
Second = new TestClass(2);
Third = new TestClass(3);
}
private TestClass(int pId)
{
Console.WriteLine("TestClass({0}) instance ctor called...", pId);
Id = pId;
}
}
}
TestClass() static ctor called...
// the line "First = new TestClass(1);" now triggers the base class static ctor to be called,
// but the fields First, Second, and Third are all still equal to null at this point!
FillAll() called...
TestClass(1) instance ctor called...
TestClass(2) instance ctor called...
TestClass(3) instance ctor called...
// this null reference exception to be expected because the field value actually was null when FindAll() added it to the list
Unhandled Expecption:
System.NullReferenceException: Object reference not set to an instance of an object.

C# How to treat static class as a variable

I have a static Class and within it I have multiple public static attributes. I treat this class as my global class.
However now I need to treat this class as a variable so that I can pass it to a method of another class for processing..
I can't instantiate this class.. So in effect I can only assign the variables inside this class.
Is my understanding correct or am I missing something?
public static class Global
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
Let say I have a class like this, and I need to somehow keep a copy of this in another class maybe
public static class Global_bk
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
I need to copy the contents from Global to Global_bk.
And after that I need to compare the contents of the two classes in a method like
static class extentions
{
public static List<Variance> DetailedCompare<T>(T val1, T val2)
{
List<Variance> variances = new List<Variance>();
FieldInfo[] fi = val1.GetType().GetFields();
foreach (FieldInfo f in fi)
{
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (!v.valA.Equals(v.valB))
variances.Add(v);
}
return variances;
}
}
class Variance
{
string _prop;
public string Prop
{
get { return _prop; }
set { _prop = value; }
}
object _valA;
public object valA
{
get { return _valA; }
set { _valA = value; }
}
object _valB;
public object valB
{
get { return _valB; }
set { _valB = value; }
}
}
So on my main form, how do I go about calling the compare method and passing the static Global class inside?
example: extentions.DetailedCompare(Global, Global_bk) ? Of course this would give me an error because I cant pass a type as a variable.
Please help me, this is driving me nuts...
How about the singleton pattern ? You can pass reference to shared interface (IDoable in exable below) and still have just one instance.
I.E.:
public interface IDoable {
int Value { get; set; }
void Foo();
}
public static class DoableWrapper {
private MyDoable : IDoable {
public int Value { get;set; }
public void Foo() {
}
}
private static IDoable s_Doable = new MyDoable();
public static IDoable Instance {
get { return s_Doable; }
}
}
Singleton is the way to go here. You can do it like this:
internal class SomeClass
{
private static SomeClass singleton;
private SomeClass(){} //yes: private constructor
public static SomeClass GetInstance()
{
return singleton ?? new SomeClass();
}
public int SomeProperty {get;set;}
public void SomeMethod()
{
//do something
}
}
The GetInstance Method will return you a SomeClass object that you can edit and pass into whatever you need.
You can access the members with classname.membername.
internal static class SomeClass
{
public static int SomeProperty {get;set;}
public static void SomeMethod()
{
//do something
}
}
static void main()
{
SomeClass.SomeProperty = 15;
SomeClass.SomeMethod();
}
The only way you are going to obtain a variable with the "class" information is using reflection. You can get a Type object for the class.
namespace Foo {
public class Bar
{
}
}
Type type = Type.GetType("Foo.Bar");
Otherwise, if you are really describing a class "instance" then use an object and simply instantiate one.
C# offers no other notation for class variables.

Categories