adhoc struct/class in C#? - c#

Currently i am using reflection with sql. I find if i want to make a specialize query it is easiest to get the results by creating a new class inheriting from another and adding the 2 members/columns for my specialized query. Then due to reflections in the lib in my c# code i can write foreach(var v in list) { v.AnyMember and v.MyExtraMember)
Now instead of having the class scattered around or modifying my main DB.cs file can i define a class inside a function? I know i can create an anonymous object by writing new {name=val, name2=...}; but i need a to pass this class in a generic function func(query, args);

Have a look at the DynamicObject maybe it could serve your needs if you hide a Dictionary
behind your implementation of TryGetMember/TrySetMember.
There is a small example on this, follow the link.

Classes (types in general) can not be defined inside methods. Doh.

It's possible (although not simple), but then the resulting class would not be known at compile time, so you wouldn't be able to use v.MyExtraMember. You would basically get a dynamically created anonymous object, so you would have to use reflection to access the extra members.

Related

Generic/DRY way to return Dictionary<string, T>

I have a CSV parser that takes the text line-by-line and parses it to values. I'm trying to put these values in a Dictionary<string, T> and return it, where T is a descendant of class CharacterStatElement. I do know what class I want T to be when I parse the CSV, but I don't want to have to rewrite/copypaste the same parser function several times to cover each Type that I want to return from it.
Should I be writing a Generic Method for the whole thing (and if so, how do I declare that in the Method and return?) or should I be doing some other pattern here?
Further info on the CharacterStatElement: Each of the child classes contains several fields that I figure out in the parsing using reflection. Each of the child classes has different values, but they ought to all be parsed the same way. Also, this only happens once per button click, not on a loop, so speed isn't an issue. And extracting the meat of the method to wrap it in non-generic methods doesn't do me much good, because most of the parsing method is tied to what the intended Type is by my use of reflection.
You can use a generic method. In order to use reflection on the type parameter you can get a Type object using typeof(T). That way you can instantiate that type and set properties dynamically. This is a rather bad case for generics. If you just used object instead of T everything would pretty much work the same way. That's a sign generics are not needed.
You also could pass in a "strategy" into the generic function that knows how to convert the raw parsed fields (probably a string[]) into a T. That strategy would be a Func<string[], T>. That way there is no reflection at all and this is a clean use case for generics.
Or, make the CSV parser return an IEnumerable<string[]> and deal with the conversion to T outside of the CSV parsing method.
I would suggest that the CharacterStatElement class have a method that knows how to parse the remaining of the input line. Each derived class is overridden to perform its specific parsing process. Add any helper methods to the base class so minimize coding needed in the derived classes.
Then you process each line of the CSV file in the following way. Parse the start that gives you the information you need to decide on the correct class for parsing the whole line. Then create an instance of the correct derived class and pass in the line for processing. Then add to your global dictionary the values. Simple.

Typecast classes

I have two classes in different namespaces which I need to type cast.
How to type cast object of one class in another. Both the classes have same method and properties.
May reflection will work?
Any example of typecasting of classes will be helpful.
You cannot cast directly from one type to another, you can do:
a manual mapping
map automatically using reflection (as propery names are the same)
Use AutoMapper
You cannot cast them unless they are related in some way, for example, one is the base of other.
You can map from one to the other in many different ways, one would be by using a mapper, AutoMapper is a well known one
https://github.com/AutoMapper/AutoMapper
This wil map from one to the other based on class member names
Another solution (a part form mapping) in case when the classes are not related in any way, can be use of dynamic.
Event if this is too dangerous, but can be considered like one of possible options:
namepsace A {
public class NotRelatedA() {
public void Run() {}
}
}
namepsace B {
public class NotRelatedB() {
public void Run() {}
}
}
dynamic dyn = new A.NotRelatedA();
dyn.Run(); //Run A
dyn = new B.NotRelatedB();
dyn.Run(); //Run B, without changing and mapping anything
Repeat, this is kind of dangerous, as you leave safe static type world, and jump into the dynamic powerfull mess, so if you use it, use it with causion.
How many properties do those classes have? Are they "hand-written" classes?
Maybe you don't need two classes and can delete one of them and use the other one everywhere?
Maybe one of the classes could derive from the other? Then you will only have to write the common properties and method in the base class.
If you need two distinct classes, and neither derives from the other (this is the situation one msut have for "ordinary" casts (reference conversion casts) to be allowed), you have several options:
Write a constructor overload for one of the classes that takes in an instance of the other class as a parameter, or
Write a static method that "translates" an instance of one class to a new object of the other type, or
You could write a public static explicit operator ClassOne(ClassTwo ct) that did the "translation". With that, it's allowed to use standard cast syntax (i.e. say (ClassOne)variable), or
As others have suggested, you could use a mapping tool, or write your own reflection code that finds the properties that "look alike" a translate between them.

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.

C++ equivalent of Java's Linked List / C#'s Array List?

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>

When do we use a nested class in C# [duplicate]

This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 9 years ago.
Would like to know when it is right to uses a nested classes in C#?
Do we have incidents in which the use of it is unjustified and therefore not correct?
If you can give examples for both situations
Thanks
I find it's convenient to use a nested class when you need to encapsulate a format of data that is primarily going to be used within the parent class. This is usually because the purpose or format of the data is so bespoke to the parent class that it's not really suitable for wider use within your solution.
Here's a simple basic introduction to nested classes.
Nested_Classes
C# doesn't have a way to write a using directive to target a class, so that the static members of the class can be accessed without writing the class name as a qualifier (compare with Java's import static, which does allow that).
So for users of your classes, it is a little more convenient if you make any public classes as direct members of a namespace, not nested within other public classes. That way they can pull them into the global namespace with a using directive.
For private classes, go nuts, preferably put them close to where they are used to enhance the readability of your code.
I am not sure if there is room in my world for nested classes. It simply blurs the design for me. If you need to hide the information inside a class, why not just store it in member variables?
Besides, testing becomes more cumbersome without the ability to inject a stub in the place of the class.
User of Nested class is depending upon the scenario like below.
1) Organizing code into real world situations where there is a special relationship between two objects.
2) Hiding a class within another class so that you do not want the inner class to be used from outside of the class it is created within.
Suppose you have 2 classes called A and B and class B is depending upon class A without class A you cannot use class B # that scenario you can use nested classes
As per my knowledge
DataRow class is nested class for DataTable
i.e you cannot create a DataRow Class untill u declare a object of DataTable class
I find two main resons:
Personalize a class' name without ruining it.
Example: Vercas.ExplorerView, where I personalize the name of my class without ruining the meaning.
Private classes.
Example: Vercas.ExplorerView.Item is used only inside Vercas.ExplorerView.

Categories