c# - How does a Generic Method Work? -



c# - How does a Generic Method Work? -

i picked tutorial on msdn allow user of app alter , save settings. after head scratching think understand of it, except 1 thing. let's start relevant part of original code. stands in class called appsettings. property i'm using test son1. understand this:

at end of code, got this:

// property , set son1 key. public int son1 { { homecoming getvalueordefault<int>(son1keyname, son1default); } set { if (addorupdatevalue(son1keyname, value)) { save(); } } }

if set property, it's easy. calls method:

public bool addorupdatevalue(string key, object value) { bool valuechanged = false; // if key exists if (settings.contains(key)) { // if value has changed if (settings[key] != value) { // store new value settings[key] = value; valuechanged = true; } } // otherwise create key. else { settings.add(key, value); valuechanged = true; } homecoming valuechanged; }

i have , i'm done:

appsettings param = new appsettings(); param.son1 = 1;

now syntax thing seems more unusual me . process same, method used property. property listed @ top of post. can see, calls method:

public t getvalueordefault<t>(string key, t defaultvalue) { t value; // if key exists, retrieve value. if (settings.contains(key)) { value = (t)settings[key]; } // otherwise, utilize default value. else { value = defaultvalue; } homecoming value; }

i'm disturbed "t", written between < , >. if understand it, should able set property default value, wich i'll propably @ origin of program. tip appreciated. give thanks you.

it's syntax generics.

this complex subject, few words: it means method can used multiple types. simplify, can replace t type. instead of writing multiple functions:

public string getvalueordefault(string key, string defaultvalue) public int getvalueordefault(string key, int defaultvalue)

you write one:

t getvalueordefault<t>(string key, t defaultvalue)

c# generics

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -