Best way to implement extension methods - linq

I am really really really new to all of this, and most of it is unexplored territory. Today I needed to create an anonymous class and put it to a list. I was trying to find how I can make a list of anonymous types, and found that I should make an extension method. I also already figured out an extension method should be in a static class. But what I haven't figured out yet is if there is some pattern that I should use? For now, I have made a static class in my App_Code folder named ExtensionMethods, but have no idea if I should put extension methods of all kinds of types in this class, or if I should make separate classes etc.

To my knowledge you can not implement extension methods for anonymous classes. And this makes sense as really and truly if the class has some semantics it should be made a named class.
To create a list of anonymous classes use this method:
public static List<T> CreateListFromType<T>(T anonType){
return new List<T>();
}
To use this method to create a list, do something like:
var list = CreateListFromType(new {A = default(int), B = default(int)});

Extension method is nothing more than easier-to-read static helper/utility methods. The way you organize them is the same principal as how you organize your normal classes. If you think those should stays together, then try to give them a meaningful, general enough name as the class name. Once you found your class name cannot include what that method doing, then you know that method should belongs to other places.

Firstly extension methods are normal static methods declared like this -
void MyExtension(this MyTarget target, int myparam){ ..
After this the C# compiler adds some syntactic sugar letting you call this method as
target.MyExtension(myparam);
The compiler will replace all these calls with
MyStaticClass.MyExtension(target, myparam);
The important thing is that an extension method is a normal static method. You should follow following guidelines while creating them -
Try to group extension methods for each target class in a separate static class and name it appropriately as Extensions.
Create a new namespace in your application for Extension methods such as MyAppExtensions and keep your static classes inside this namespace. This will keep the coder from misunderstanding them as Extension method and accidentally using them as instance methods.
Make these naming conventions for namespaces and static classes of Extension methods as a standard in the team.
In your extension method check if the first parameter is null and take appropriate action. If you do not then it will be possible to call the method with target being null and may result in unexpected behavior. If the first parameter is allowed to be null then document it clearly.
Consciously decide if it is correct to create and extension method or instance method will be better.
Be careful that the extension method names do not clash with instance method names or other existing extension method names for this class. Following point 1, 2 and 3 will help you achieve this.
I learnt these from Jon Skeet's C# In Depth. You should read it too.

This is how you create a list of an anonymous class.
var anonList = new[]{
new {Foo = "foo", Bar = 2},
new { Foo = "bar", Bar = 3},
}.ToList();
It has nothing to do with writing extension methods.
Edit:
In fact you will have a hard time to use extension methods to create anonymous types since anonymous types can not be used as method parameters or return type.
Edit2:
If you want to convert a list of anonymous types to a list of specific types you can use Select:
class MyClass
{
public string Prop1 {get;set;}
public int Prop2 {get;set;}
}
List<MyClass> myList = anonList.Select(x => new MyClass(){Prop1 = Foo, Prop2 = Bar}).ToList();

I use to put anonymous to DataTable. Due to it's limitation, DataTable provide more functionality such as serialization.

Related

Are there penalties for just using the new keyword instead of creating a class variable before calling the class method?

Example
(1)
var classVar = new class();
classVar.Method();
(2)
new class().Method();
I like the second way, less wordy.
Is there a performance difference?
Is it considered bad coding practice?
If your Method() doesn't use anything from that class, why is it defined there? You could use namespace instead.
The only difference between your (1) and (2) is that the class instance is destructed immediately in (2).
in your case Method seems to be static (ie there is no useful data stored inside the instance of 'class' (note I am ignoring all the invalid / not recommended name issues). Assuming this is c# but all languages have the same ideas, you would go
public class class{ // ugh
public void static Method(){
Console.WriteLine("I am Method");
}
}
now you can go
class.Method();
so the code is neatly filed away inside 'class' but you dont have to pay any overhead.
If you really need to instantiate 'class' then presumably you need to do more than just call one method on it. In which case
new class().Method();
makes no sense, since you call create it, call a method and destroy it.
Really a more concrete example is needed

How to check where a who calls this method?

I have a custom method in an ABAP class.
I used the 'Where used' tool to show where the class is called from but, as it turns out, it's called from somewhere else I didn't expect.
So what's the best way of showing a complete list of everything that calls the method?
Due to the wonders of object-oriented programming, an instance of a class can hide behind a reference to one of its base classes or interfaces it implements. For example:
DATA foo TYPE REF TO z_my_interface.
CREATE OBJECT foo TYPE z_my_class.
" lots of more code
foo->bar( ).
You can not find this reference to z_my_class->foo with its "Where Used" list, because at that code location foo could also be a reference to an instance of any other class which implements z_my_interface. But you might be able to find this if you don't just look at the where-used list of the method but at the where-used list of the whole class or the interface / base class which declares the method.
And then there are evil dynamic programming tricks like this which determine methods and classes at runtime:
DATA foo TYPE REF TO object.
CONSTANTS: classname TYPE string VALUE 'Z_MY_CLASS',
methodname TYPE string VALUE 'BAR'.
CREATE OBJECT foo TYPE (classname).
CALL METHOD foo->(methodname).
There is no chance to find this with the where-used tool. But if the class- and/or method name does actually appear in the code (it might not, for example if they are read from a customizing table) then you can use the report RS_ABAP_SOURCE_SCAN. This handy little tool allows you to select a set of ABAP programs and search for strings (and even regular expressions) within their sourcecodes.
However, if you know the method gets called when you do something specific as a user and just want to know where, then it can be easier to just set a debugger breakpoint in the method, run into it and check the call stack.
Sorted using the code_scanner transaction.

How do I discern whether a Type is a static array initializer?

I'll start by saying that I'm working off the assumption that static array initializers are turned into private nested classes by the compiler, usually with names like __StaticArrayInitTypeSize=12. As I understand it, having read this extremely informative article, these private classes are value types, and they aren't tagged with the CompilerGeneratedAttribute class.
I'm working on a project that needs to process certain types and ignore others.
I have to be able to process custom struct types, which, like the generated static array initializer classes, are value types. I must ignore the generated static array initializer classes. I also must ignore enumerations and delegates.
I'm pulling these classes with Linq, like so:
var typesToProcess = allTypes.Where(type => !type.IsEnum &&
!type.IsArray &&
!type.IsSubclassOf(typeof(Delegate)));
I'm fairly sure that the IsArray property isn't what I think it is. At any rate, the generated static array initializer class still shows up in the typesToProcess Enumerable.
Has anyone else dealt with this? How can I discern the difference between a custom struct and a generated static array initializer class? I could hack it by doing a string comparison of the type name against __StaticArrayInitTypeSize, but is there a cleaner solution?
Well, having just tried it myself with the C# 4 compiler, I got an internal class called <PrivateImplementationDetails>{D1E23401-19BC-4B4E-8CC5-2C6DDEE7B97C} containing a private nested struct called __StaticArrayInitTypeSize=12.
The class contained an internal static field of the struct type called $$method0x6000001-1. The field itself was decorated with CompilerGeneratedAttribute.
The problem is that all of this is implementation-specific. It could change in future releases, or it could be different from earlier releases too.
Any member name containing <, > or = is an "unspeakable" name which will have been generated by the compiler, so you can view that as a sort of implicit CompilerGenerated, if that's any use. (There are any number of other uses for such generated types though.)

Elegant Asp.Net MVC 3 custom membership wrapper class with extended (custom) methods and properties

I am attempting to write a custom membership class. It seems to work ok inhering the Membership class and providing functions for all the included required items (validate user, create user, delete user, isapproved, etc).
However, where I run into a problem is when I try to add properties or methods.
As all the other properties and methods are public override classes in a sealed class,
the additional properties do not show up.
Say for example (example only, not "real" code):
public sealed class Membership : MembershipProvider
{
public override string ApplicationName
{
get
{
return "myApp";
}
}
public string myValue { get;set;}
}
Now, I understand why myValue will not show up when I try to do Membership.myValue but Membership.ApplicationName will.
My question is, how to extend membership to show the custom items? Do I ditch Membership.xxx entirely and write a wrapper class? If so, how? I can find all the documentation in the world on how to create a custom membership class. I've got a working custom membership that works fine if I use all the available options only. I've got a custom roles provider and a custom config section to store everything and it's best friend.
What I don't have is an elegant solution.
I'd like the end result to be that I use one reference (such as Membership.xxx or myClass.xxxx) to reference all membership items + custom items.
Please provide examples of how to implement or links to appropriate items that will resolve the custom methods item.
Any time you reference the membership instance you will just have to cast it to your class type, that's all.
You can take a look at Extension Methods if you don't want to cast back and forth your instances

Where do you add new methods?

When you add a new method to a class where do you put it? At the end of the class...the top? Do you organize methods into specific groupings? Sorted alphabetically?
Just looking for general practices in keeping class methods organized.
Update When grouped where do you add the new method in the group? Just tack on the end or do you use some sort of sub-grouping, sorting?
Update 2 Mmmm...guess the question isn't as clear as I thought. I'm not really looking for class organization. I'm specifically interested in adding a new method to an existing class. For example:
public class Attendant
{
public void GetDrinks(){}
public void WelcomeGuests(){}
public void PickUpTrask(){}
public void StrapIn(){}
}
Now we're going to add a new method PrepareForCrash(). Where does it go? At the top of the list, bottom, alphabetically or near the StrapIn() method since it's related.
Near "StrapIn" because it's related. That way if you refactor later, all related code is nearby.
Most code editors allow you to browse method names alphabetically in another pane, so organizing your code functionally makes sense within the actual code itself. Group functional methods together, makes life easier when navigating through the class.
For goodness sake, not alphabetically!
I tend to group my functions in the order I expect them to be called during the life of the object, so that a top to bottom read of the header file tends to explain the operation of the class.
I think it's a personal choice.
However I like to organise my classes as such.
public class classname
{
<member variables>
<constructors>
<destructor>
<public methods>
<protected methods>
<private methods>
}
The reason for this is as such.
Member variables at the top
To see what member variables exist and if they are initialised.
Constructors
To see if the member variables are setup/initialised as well as what are all the construction options for the class.
Destructor
To see the how the class is cleaned up and verify it with the constructors and member variables.
Public methods
To see what are the available contracts callers of the object can use.
Protected methods
To see what inherited classes would be using.
Private methods
As it's information about the internals of the class if you needed to know about the internals you can just scroll straight to the end quickly. But to know the interface for the class it's all at the start.
UPDATE - Based on OP's update
Logically a good way would be to organise the methods by categories of what they do.
This way you get the readabilty of categorising your methods as well as the alphabetical search from you IDE (provided this is in your IDE).
However in a practical sense I think placing the methods at the end of that section is the best way. It would be quite hard to continually police where each method goes, as it's subjective, for every method if the code is shared by more than yourself.
If you were to make this a standard it'd be quite hard to provide the boundaries for where to put each method.
What I like about C# and VB.net is the ability to use #region tags, so generally my classes look like this
class MyClass
{
#region Constructors
public MyClass()
{
}
public MyClass(int x)
{
_x = x;
}
#endregion
#region Members
private int _x;
#endregion
#region methods
public void DoSomething()
{
}
#endregion
#region Properties
public int Y {get; private set;}
#endregion
}
So basically You put similar things together so you can collapse everything to definition and get to your stuff really faster.
Generally, it depends on the existing grouping; if there's an existing grouping that the new method fits into, I'll put it there. For example, if there's a grouping of operators, I'll put the new method with the operators if it's an operator.
Of course, if there is no good grouping, adding a method may suggest a new grouping; I treat that as an opportunity for refactoring, and try to regroup the existing operators where reasonable.
I organize all methods into regions like public methods, private methods or sometimes by features like Saving methods, etc..
IMHO:
If you organize your methods alphabetically, put a new one depends on its name. Otherwise put it at the bottom of related group. This helps to know, what method is newer. The bigger problem is how to organize methods in groups, e.g. depend on what properties, but this is more individual for everyone and depends on a specific class.

Resources