Tuesday, May 1, 2012

generics and types

So today I came across

And to be honest, I have no idea what T really was. I assumed it had to do with typecasting, but wasn't sure exactly how it was used here. So it seems like it's a "name" and not a keyword, which is good since it's just a letter. But still, it seems like it's something that I needed to learn a bit more about. 

Looking into my C# book I find a section on Generics which seems promising. My book says something about Generics offering better static typing, but from my past experience static typing just makes using variables more strict. I hate putting limitations on how easily i can use a letter or number.

Both of these things infer that you need to add
using System.Collections.Generic and possibly System.LINQ, but I commented the two statements, and the code still compiles fine with the <T> in the function. Not sure why that is since it's inferring that <T> is something that comes out of one of those two references. Am I missing something? why is this working without those two references?

public Diddly something<Diddly>(Diddly someValue)
{
Diddly squat;
squat = someValue;
return squat;
}

why, exactly, is that chunk of code valid C#? I'm not completely clear as to how Diddly is used and why squat can be Diddly. This all seems a bit weird to me. I'll have to experiment with that it all means. Microsoft says to use <T> and not <Diddly> just out of using standards, but to me T is no more descriptive than Diddly. I suppose they're trying to say that it's a T for Type, but why not just use <GenericType> instead of <T> for the sake of being descriptive or expressive as people like to say about C# and F# and the other # languages.
Adding in a debug line i get this...
So T is a string. a string type of string, which i'd imagine it should be. But why the <T> ?
So what if i turn all of the Ts into string?


This gives me this error and it tells me it doesn't like types as identifiers. So, that tells me that C# is actually looking at all of the instances of the T as a variable of some kind. But why? how are all of these things being used?
Visual studio has a helper that would like to tell me that to fix this the first place where T should be it's asking:
If it would like the T to be a class or type, but it just said it didn't want types. Either way, neither of those generated objects were valid.


This is confusing though, somehow this is valid? Why? <int> and <string> what are these and how do they work? Thought I was trying to learn something today, instead so far I'm just getting confused.




No comments:

Post a Comment

rxokita's shared items