I have a VB background and I'm converting to C# for my new job. I'm also trying to get better at .NET in general. I've seen the keyword "T" used a lot in samples people post. What does the "T" mean in C#? For example:
public class SomeBase<T> where T : SomeBase<T>, new()
What does T do? Why would I want to use it?
It's a symbol for a generic type parameter. It could just as well be something else, for example:
public class SomeBase<GenericThingy> where GenericThingy : SomeBase<GenericThingy>, new()
Only T is the default one used and encouraged by Microsoft.
T is not a keyword per-se but a placeholder for a generic type. See Microsoft's Introduction to Generics
The equivalent VB.Net syntax would be:
Public Class SomeBase(Of T As {Class, New}))
A good example of another name used instead of T would be the hash table classes, e.g.
public class Dictionary<K,V> ...
Where K stands for Key and V for value. I think T stands for type.
You might have seen this around. If you can make the connection, it should be fairly helpful.
That would be a "Generic". As people have already mentioned, there is a Microsoft explanation of the concept. As for why the "T" - see this question.
In a nutshell, it allows you to create a class/method which is specialized to a specific type. A classical example is the System.Collections.Generic.List<T> class. It's the same as System.Collections.ArrayList, except that it allows you to store only item of type T. This provides type safety - you can't (accidentally or otherwise) put items of the wrong type in your list. The System.Collections.Generic namespace contains several other different collection types which make use of this.
As for where you could use it - that's up to you. There are many use-cases which come up from time to time. Mostly it's some kind of a self-made collection (when the builtin ones don't suffice), but it could really be anything.
Best way would be to get yourself familiar with "Generics", many resources on the web, here's one
T is not a keyword but a name, could be anything really as far as I know, but T is the convention (when only one type is needed, of coruse)
The T is the name for the type parameter in a generic class. It stands for "Type" but you could just as well call it "Alice."
You use generics to increase reusability in a type-safe manner without needlessly duplicating code. Thus, you do not need to write classes for ListOfIntegers, ListOfStrings, ListOfChars, ListOfPersons and so on but can instead write a generic class List<T> and then instantiate objects of types List<Int32>, List<string>, List<char> and List<Person>. The compiler does the work for you.
It means "any class". It could be "B", "A", whatever. I think T is used because of "Template"
Related
I have an existing base type and I would like to cast it to a derived type base upon the name of the type as a string, so something like this:
public void DoStuffInDerivedType(string derivedName) {
(base as Type.GetType(derivedName)).DoThisThing();
}
I'm pretty sure this can't be done but would be good to know for sure. Thanks
EDIT: I understand that I could construct the object using reflection from the type name but I want use an existing object. And also I know this is generally a bad idea. However I wanted to use this for a SpecFlow BDD Feature.
I'll repeat the advice that you probably don't need to do this, but because I have done this operation before:
Convert.ChangeType(ItemToCast, Type.GetType(stringNameOfType)))
Should work for you.
I don't think you need to cast it to the derived type. You should be able to cast it to the base type and use the shared interface (be it a base class or literal Interface) to perform whatever you want done.
If not, consider adding the behavior as an interface requirement so you can do it that way.
Finally: the one possibility where you'd need to do it this way is if you're overriding the casts...in which case I'm almost certain you can't do this without some heavy duty reflection.
Aren't classes supposed to be called after objects and not actions? It just does not sit along with OO theory I learned.
One thought was that maybe since Convert holds only static methods then no instances of it are supposed to be created at all, which might make it an acceptable exception.
In C# you can't create methods outside classes or structs. So when you want to create utility methods, it's best to store them in a static class.
So i would say that there's nothing object oriented about a static class.
There's nothing object-oriented about the Convert class, because object-orientation is about data with behaviour, and the Convert class holds no data or state.
It's basically a practical consideration.
In Eiffel, for example, the conversion methods would have been defined in a base class, and all classes needing to use the conversion methods would have derived from that base class. However, Eiffel has multiple inheritance, so that makes sense for Eiffel, but not for a language like C# where you don't have multiple inheritance.
Your thought is correct. Convert is a static utility class, with one purpose - converting between different types.
It has only methods (verbs), which all of them are conversions - so, for readability, it's better to give the name of the common verb to the class itself, than to repeat it in every method:
int i = Convert.ToInt32(value);
float f = Convet.ToSingle(value);
are much more fluent and readable than:
int i = Conversions.ConvertToInt32(value);
float f = Conversions.ConvertToSingle(value);
My personal opinion is that is OK for Convert class to be called after action, because it's a static class, and will not be instanced.
It simply sounds better to call
Convert.ToBoolean(var);
instead of
Converter.ConvertToBoolean(var);
Naming conventions are funny beasts. The most important thing is consistency across a framework.
Needless to say, OO conventions can real help architecture legibility. In this case, the convert class and its static methods are best attempt replacements for global functions using c# and are given a fluid names to indicate as such.
Convert [parameter] to Int32
Convert [parameter] to Single
By naming them as actions, not objects, we also communicate functional purity.
This is often seen in the singleton pattern as well with the Instance property.
I have an array of different object types (about 15 different types) , they are coming from 3rd party system.
For every type I need to make different transformation.
My original thought is to make some interface with transform function and for every type make a class and run it's own implementation.
But like this I will need to make a really big if statement that checks the object type and make the mapping.
I am trying to learn something new here, so my question is there other ways to deal with this situation?
Have you considered the possibility of using a Visitor?
If you combine the visitor pattern with the use of dynamic, you could get a pretty simple implementation without any if or switch statements, or having to manually create a Type Dictionary with delegates, or similar alternatives.
Using dynamic you can avoid implementing the "accept" part of the design pattern, which I assume is useful to you since these are external types you have no control over.
Meaning, you create something like this:
public interface IVisitor
{
void Visit(OneType element);
void Visit(AnotherType element);
....
}
You implement that visitor, and can later call the implementation using:
visitor.Visit((dynamic)objectToTransform);
You would probably have to handle for exceptions regarding not having an appropriate overload for the Type.
That would solve the part of the problem related to executing a separate method for each type.
Now, depending on what you specifically need to do with each one, if you need automatic property mapping then AutoMapper could be very useful.
You can create a lookup of type and transformation, similar to Java Front Controller pattern.
I'm not sure if this is what you want, but have a look at AutoMapper (or aother mappers). It allows you to easily define rules to map types to other types.
Is there an STL container or something else that gives the same functionality as Java's Linked List or C#'s Array List? i.e appending different types into the same array like
List.Append(1);
List.Append("I am a string");
List.Append(True);
and dynamic functions like
List.Resize();
List.GetSize();
etc.?
If not , can u implement one yourself using templates etc.? If so, How?
It's hard to implement this using templates because templates assume a single type for members. In C++ you'll have to use polymorphism with a common source (which is available in Java and C# as a common "Object" parent for all the classes, IMHO).
You can try to do it using the boost library, and the boost::variant or boost::any (choose which one fits your needs).
First off, ArrayList in C# and LinkedList in Java are fundamentally different beasts (one implements a resizable array while the other implements a linked list).
Secondly, ArrayList in C# (but not in Java) is deprecated; use the generic List<T> instead (in your case, a List<object>).
Thirdly, this corresponds to std::vector in C++.
If you need to insert different types into it, you got three basic choices:
Use Boost.Any
Use Boost.Variant
Use a common base class. This is the most sensible alternative in 95% of the cases.
You could use boost::any and then a std::list.
Take a look at the examples of the boost homepage.
You can combine std::list with boost.Variant as type T.
Java/C# manage this by having an Object class that all classes derive from. C++ does not have this root.
If all your data is in a class hierarchy then you can use a std::list or vector of pointers (bare or smart) to the root class.
If not then you need to use an adaptor to make them appear the same class e.g. boost::variant and then make a list of those. e.g. std::list<boost::variant>
Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python?
The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was.
But, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this mechanism to provide statically type checking.
So, dynamic ( OO ) programming languages do use interfaces, even thought they don't statically check them. Just like other data types, for instance in Ruby:
#i = 1;
You don't have to declare i of type FixNum you just use it. Same goes for interfaces, they just flow. The trade-off is, you can't have a static check on that and failures are only show at runtime.
In the other hand Structural type ( or static duck type as I call it :P ) used by languages as Go or Scala, gives the best of both worlds.
1. See Daniel Earwicker comment about CORBA interface keyword
We don't require them, but we do support them. Check out Zope Interfaces (which can be and are used outside of Zope).
It's worth noting that, contrary to what many people will say as a first response, interfaces can be used to do more than document "what methods a class supports". Grzenio touches on this with his wording on "implement the same behaviour". As a specific example of this, look at the Java interface Serializable. It doesn't implement any methods; rather it's used as a "marker" to indicate that the class can be serialized safely.
When considered this way, it could be reasonable to have a dynamic language that uses interfaces. That being said, something akin to annotations might be a more reasonable approach.
Interfaces are used in statically typed languages to describe that two otherwise independent objects "implement the same behaviour". In dynamically typed languages one implicitly assumes that when two objects have a method with the same name/params it does the same thing, so interfaces are of no use.
One key thing about at least some dynamic languages that makes explicit interfaces more than a little awkward is that dynamic languages can often respond to messages (err, “method calls”) that they don't know about beforehand, even doing things like creating methods on the fly. The only real way to know whether an object will respond to a message correctly is by sending it the message. That's OK, because dynamic languages consider it better to be able to support that sort of thing rather than static type checking; an object is considered to be usable in a particular protocol because it is “known” to be able to participate in that protocol (e.g., by virtue of being given by another message).
Interface constructs are used in statically typed languages to teach the type system which objects are substitutable for each other in a particular method-calling context. If two objects implement the same method but aren't related through inheritance from a common base class or implementation of a common interface, the type system will raise an error at compile time if you substitute one for the other.
Dynamic languages use "duck typing", which means the method is simply looked up at runtime and if it exists with the right signature, it's used; otherwise a runtime error results. If two objects both "quack like a duck" by implementing the same method, they are substitutable. Thus, there's no explicit need for the language to relate them via base class or interface.
That being said, interfaces as a concept are still very important in the dynamic world, but they're often just defined in documentation and not enforced by the language. Occasionally, I see programmers actually make a base class that sketches out the interface for this purpose as well; this helps formalize the documentation, and is of particular use if part of the interface can be implemented in terms of the rest of the interface.
Perl has Roles (or traits ), It is more than interfaces unlike java perl roles we can have a implementation check out these links for more on perl roles
http://en.wikipedia.org/wiki/Perl_6#Roles
http://use.perl.org/~Ovid/journal/38649
In C# and Java, interfaces are just abstract classes with all abstract methods. They exist to allow pseudo multiple-inheritance without actually supporting full-blown multiple inheritance and the ambiguity multiple inheritance creates.
Python supports multiple inheritance and has its own way of determining which parent's method should be called when a method exists in multiple parents.
Dynamic languages are Duck Typed
If it walks like a duck and quacks
like a duck, it must be a duck
http://en.wikipedia.org/wiki/Duck_typing
In other words, If you exect an object to suport the Delete() method, than you can just use the
obj.Delete()
method but if the object doesn't support Delete() you get a Runtime error. Statically typed languages wouldn't allow that and throw a compile time error. So you basically trade type safty against faster developement time and flexibility.
Without interfaces you can do something like that in static languages:
void Save(MyBaseClass item)
{
if (item.HasChanges)
item.Save()
}
but that would require every object that you pass to this method to inherit from MyBaseClass. Since Java or C# don't support muliinheritance that isn't very flexible because if your class already inherits another class it cannot inherit from MyBaseClass, too. So the better choise would be to create a ISavable interface and accept that as a input parameter to ensure that item can be saved. Then you have best of both: type safety and flexibility.
public interface ISavable
{
bool HasChanges {get;set;}
void Save();
}
void Save(ISavable item)
{
if (item.HasChanges)
item.Save()
}
The last backdoor is to use object as a parameter if you cannot expect every item that will use your save method to implement the interface.
void Save(object item)
{
if (item.HasChanges)
item.Save()
}
But than again, you don't have compile time checking and probably get a runtime error if someone uses your method with an incompatible class.