how is a tuple different from a class? - c#

how is a tuple different from a class? instead of the following code, we can make a class with 3 fields and make objects from it. How is this Tuple different from that? Is it only reducing the code we write or does it have something to do with speed as well, given the fact that you can't change the items in a tuple.
Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true);

It saves you from having to define a new class with custom properties.
It does define equality by the value of the three items, which is something that a bare-bones class would not do without custom coding. That plus the fact that it's immutable makes it a reasonable candidate for a hash key in a Dictionary.
One drawback is that the properties are vanilla Item1, Item2, etc., so they don't provide any context to the values within them, where properties like ID, Name, Age would.

Tuple is a class. One that holds any data you want (in terribly named properties like Item1).
You should be making classes instead so your code is more readable/maintainable. Its primary function is as a "quick fix" when you want to associate pieces of data without making a class to hold them.

Tuples are in my opinion an invitation to bad data modeling. Instead of creating a proper model you get a generic object that can hold n item properties. The naming is very generic too.. Item1..ItemN

You use Tuples as a mean to pass data between method call without having to define a new class. Typically use to return multiple pieces of data from a method rather than use "out" parameters.
Keep in mind that out parameter cannot be use with async/await methods, this is where Tuples come in handy.
You probably want to define a class for your data if you code a reusable class library though. However, tuple is great in presentation layer.

Related

HashSet of SomeObjects and Contains function with int argument

Lets say we have class SomeObject with many fields and storing instances in HashSet.
For HashSet comprison we need only one field: int ID, so we have overriden GetHashCode() and Equals() methods.
And now my question is: Can we somehow use hashSet.Contains(someIntVariable) instead of creating whole new object of type SomeObject?
I mean if only int field is important can we use Contains function with int argument given?
I need it to check if object already exists and don't want create whole sample object.
HashSet unfortunately does not have the ability to search with a different type of objects and get what's stored. This capability could theoretically exist and maybe you can find a collection library on the web that does this.
Best workaround:
Create a separate key struct (e.g. MyKey) and use a Dictionary<MyKey, MyValue>. That way you can create a key without creating an object.
Alternatively, you could create a wrapper struct that encapsulates either a key or a whole object. You can than cheaply instantiate that struct and pass it to the HashSet. I find that to be more complicated than the first idea.

creating dispatcher for mapping functionalities

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.

How to represent (class) data for GUI generation?

I'm trying to make a small application that can edit the data files from an earlier project. I have access to that projects "data classes" (pretty dumb classes whose main purpose is to expose it's (public) member variables) that can read/write to the files. All I have to do is make a GUI that can edit the different member variables that each data class have (preferably without modifying the data class) and I'm trying to figure out how to do this so that it will be easy to adapt for future changes/additions.
(I don't feel like I can assume that all member variables should be editable, might only be a selection of them).
All the data can be converted to/from strings (numbers and text) and I don't see much problem in generating textboxes and/or something like a DataGridView in the GUI, but I'm not sure as to how I would like to represent the data needed to generate those.
My first thought was to use a list with all variables for each data class. With each row in the list containing the name+description of the variable (for the GUI), a pointer to the variable in the data-class and perhaps some form of validation-function for different variables.
Store that list in a class that inherits the original data-class (and that implements an interface/abstract-class for any specific GUI-related functions (load/save etc.)).
The thing that makes me worry about this solution is just that I feel like this should be a somewhat common problem and I'm a bit rusty when it comes to OO and this solution smells like something I'd write if I had to do it in C.
There might even be a handy language construct, design pattern or something that is suitable but I don't know what to search for.
Does this approach even seem sensible?
Reflection is your friend in this case. Your data classes have a structure which can be explored using that class's Type. A Type is the base class for metadata concerning a class or structure, and includes methods to, for instance, get a list of all fields, properties and/or methods belonging to that class. The objects representing these class "members" can then be used to set or get field or property values, or invoke methods, given an instance of an object of that type.
A reflective algorithm can be designed to handle any object structure it is given, and it doesn't have to know those structures at compile-time unlike an algorithm based on static types. The downside? It's slow, and you get very little compile-time checking of your algorithm so it can fail at run-time in unexpected ways.
Here's something to get you started:
//statically set up an instance of some arbitrary object
MyClass myObject = new MyClass();
myObject.Field1 = "Hello";
myObject.Field2 = "World";
//This method is available on any object, and produces a Type representing the class definition
Type myType = myObject.GetType();
//C# also has a typeof() keyword that works when you have a static type and not an instance
myType = typeof(MyObject);
//Interrogate the Type instance to get its fields
FieldInfo[] fields = myType.GetFields();
//then, iterate through the fields to perform some (useful?) work.
//Here, we are outputting a list of paired field names and their current values.
//You will probably want to instantiate a Label and Textbox representing this value
//and show them on a Form.
foreach(FieldInfo field in fields)
Console.WriteLine(String.Format("{0}: {1}", field.Name, field.GetValue(myObject));
To handle editability, you will need some sort of record of what the user has permission to change and what they don't. If that information will never change from user to user, you can incorporate that information into the data class itself using attributes (which won't change the "interface" of the object; it'll still have all the same members, but those members will have additional metadata). You could also create another set of classes that implement an interface defining each one as a set of "field permissions" for its parent class, and then you can dynamically construct an instance of the "field permission" class with a Type instance representing your object definition, and knowledge of the name of the interface that field permission objects implement.

Assignment between generic lists

How to assign same object list but in different namespace.
list, list2
list = list2;
Cannot implicitly convert type
System.Collections.Generic.List<namespace1.MyData> to System.Collections.Generic.List<namespace2.MyData>
This sounds to me like a WCF proxy that has been generated and you want to reuse the existing class libraries instead of the proxy generated ones.
If this is the case, then see this answer or this answer.
Edit:
as a follow up to this, occassionally you may be in the position where you can't reuse the common class definitions (in the case of Silverlight you have to create a whole new assembly which may not be practical). If you are in this position, there is another option: the proxy generated classes are defined as partial, so you can extend them with a Clone() or Copy() method that returns the identical object from the other namespace, with the values copied over.
If the objects can be cast to each other, you can do this, but it is looping though the lists and making a copy, it's not a direct assignment.
var newList = oldList.Cast<NewType>().ToList();

What does "T" mean in C#?

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"

Categories