C#, Var, and Objec- Propert- I have no idea what the term is

So I caugh this the other day and I’m not really sure it’s useful but it got me thinking…

Say you have a string and you want to create what ReSharper calls a “implicitly typed local variable declaration”, or as most people know it as “var”, and intialize it with a created value:

  String someThing = "hi";
  var onTheFly = new { someThing };

And now you can do this:

  String somethingElse = ontTheFly.something;

What it basically did was not only take the value of the string, but the name too and made a property on the var. In fact you may have seen this already with Linq:

    var hi = from item in test
               select new {item.UserRole};

    UserRole someRole = hi.ToList()[0].UserRole;

So what does this all mean? Right now, I’m not really sure. I suppose if you have a method that you want to combine a bunch of value/objects into one var so you don’t have to keep refering to 8 different objects that might work:

    //Get the user
    User user = new User (1);
    //Get some icecream... couldn't think of any better fake class name
    IceCream iceCream = new IceCream(1);

    var stuff = new { user.UserName, user.UserRoles, user.UserLastName,
                             iceCream.Flavor, iceCream.Texture };

    //IMAGINARY CODE GOES HERE
    //MORE IMAGINARY CODE
    //??
    //PROFIT
    if(stuff.UserName.Equals("Sean", StringComparison.OrdinalIgnoreCase)
       && stuff.Flavor == IceCreamFlavor.Chocolate)
    {
       //BLAH BLAH BLAH
    }

As you can see, it could be a way to group together a bunch of things in a method, but I’m not sure that is really useful.

*WARNING THIS IS NOT TO BE TAKEN AS FACT, JUST MUSINGS OF AN IDIOT*

Now for the theory… As is, this isn’t useful but with 4.0 that might change with Duck Typing and dynamic types. Why? Well take a method like this:

    CallMe(userName, userFirstName, userLastName, userAddress,
             thisIsStupid, makeItEnd, iNeedAnAdult... endMe);

Now that’s a lot of parameters. Conventional wisdom says I should create a new class whose properties match the parameters I would be sending in and just send in that class:

    parameterClass.UserName = userName;
    parameterClass.UserFirstName = firstName;
    .....
    CallMe(parameterClass);

Now the only annoying thing is having to make the class to do this. What if dynamic types + duck typing takes that step away?

    var parameter = new { userName, userFirstName, userLastName .... };
    CallMe(parameter);

Then CallMe would take in a dynamic type and just look to see if it has the needed properties. Would be nice if this is possible but I haven’t used 4.0 yet to know, I’m only guessing from what I’ve read.

Duck Typing my way to a Universal String Convert

So being the beacon of ignorance in the fog of brilliance, I had no idea what Duck Typing was. In short it’s the idea of assuming a class’s type based on the methods it holds.

Say you have 5 different classes, none of which share an inheritance tree. Now let’s say you have a method that takes in any object and uses the SeanIsAwsome method on the object. You could make sure that every object sent in has that method by using an interface that all the objects sent in share.

    public void SomeMethod(ISeanRules inParameter)

What if you want to send in a bunch of objects that don’t share the same interface/base class? Well you base it on what methods the class holds. If the class has the SeanIsAwsome method, then you call it. If not, well you could throw an exception, do nothing, go jogging, eat bacon, ect. That part is up to you.

The problem was that I wanted to create a universal convert that would take in a string and convert it to the 8 billion (ballpark figure) value types in C#. Now what I wanted to do is use the famous TryParse method so my first hope was that TryParse was a method on an interface they all shared. Yeah no. So next thought was to use the Duck Typing principle and say, “Hey jackass, you have a TryParse method? Yeah? Good. Use it.” ‘Course I had to find a way to do that. Turns out it wasn’t too bad.

public static class ConvertFromString
{
  public static T? ConvertTo<T>(this String numberToConvert) where T : struct
  {
    T? returnValue = null;

    MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));
    if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
    {
      T output = default(T);
      object[] paramsArray = new object[2] { numberToConvert, output };
      returnValue = new T();

      object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

      if (returnedValue is Boolean && (Boolean)returnedValue)
      {
        returnValue = (T)paramsArray[1];
      }
      else
      {
        returnValue = null;
      }
    }

    return returnValue;
  }
}

A whaaaa?

Ok this might look odd, but it’s really simple. If it doesn’t look odd then chances are you’re smarter than me and you shouldn’t be here anyhow. First part is simple:

  public static T? ConvertTo<T>(this String numberToConvert) where T : struct

Due to this being a extension method (Opps forgot to tell you that part) I have to declare this static method in a static class. Basically I am taking in a string and returning a nullable version of whatever type I specific in the call.

    T? returnValue = null;

    MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));

Remember that MethodInfo method I had explained in the last post? The next part you might remember too, but I’m not betting on it.

    if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
    {
      T output = default(T);
      object[] paramsArray = new object[2] { numberToConvert, output };
      returnValue = new T();

      object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

Ok so I have the method info, now I have to create the list of parameters to send in with the invoke. Pretty straight forward. If things went well, returnedValue should be a boolean. However, just incase:

    if (returnedValue is Boolean && (Boolean)returnedValue)
    {
      returnValue = (T)paramsArray[1];
    }
    else
    {
      returnValue = null;
    }

So if the returnValue is true and boolean, then the tryParse was successful. With that in mind, I still have to get the converted value. If it had not been successful than I am just going to return null since this is just meant for converting and not for whether or not it could be. It is just assumed that if it’s null, then it could not be converted at this time.

And now for the use:

  decimal? converted = someString.ConvertTo<decimal>()

An boom, you have a universal convert. YAY!

  using System;
  using System.Reflection;

Return Out Variables Using GetMethod

So I ran into a problem today. I wanted to call a method (TryParse) off a type using relfection, but the catch is that there is an out parameter. At first I though, “Hey, I just give it the type and it will find it. Not so lucky. See when you call GetMethod you have to supply a list of parameters. why? because if you don’t, the name alone could return any number of methods named the same thing. By using a parameter list, it in essence narrows it down to one. Say you look at decimal.TryParse which expects a string and an out parameter of type decimal. Would think it is:

  Type[] paramTypes = new Type[2] { typeof(string), typeof(decimal) };
  returnValue = typeToCheck.GetMethod("TryParse", paramTypes);

No dice. Looks ok until you actually look at the type of the second parameter. It’s actually “decimal&”, meaning there is a reference attached to it. This makes sense since Out will switch the pointer of the old parameter sent in to whatever you create in the method. Problem is when you trying to find the method you are looking for “decimal” != “decimal&”. Now this looks like a big problem, but it’s actually easy to solve.

  Type[] paramTypes = new Type[2] { typeof(string), typeof(decimal).MakeByRefType() };

See the difference? Turns out Microsoft already thought this one through. The MakeByRefType method allows you to simulate an out parameter. Here’s the method in full to get the MethodInfo:

  private static MethodInfo GetCorrectMethodInfo(Type typeToCheck)
  {
    //This line may not mean much but with reflection, it's usually a good idea to store
    //things like method info or property info in a cache somewhere so that you don't have
    //have to use reflection every time to get what you need.  That's what this is doing.
    //Basically I am using the passed in type name as the key and the value is the methodInfo
    //for that type.
    MethodInfo returnValue = someCache.Get(typeToCheck.FullName);

    //Ok, now for the reflection part.
    if(returnValue == null)
    {
      Type[] paramTypes = new Type[2] { typeof(string), typeToCheck.MakeByRefType() };
      returnValue = typeToCheck.GetMethod("TryParse", paramTypes);
      if (returnValue != null)
      {
        someCache.Add(typeToCheck.FullName, returnValue);
      }
    }

    return returnValue;
  }

Now we’re not done yet, are we? No. That just gets the methodInfo needed. Now how do I call it and get a value back? Well that’s pretty easy too:

  MethodInfo neededInfo = GetCorrectMethodInfo(typeof(decimal));
  decimal output = new decimal();
  object[] paramsArray = new object[2] { numberToConvert, output };
  object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

  if (returnedValue is bool && (bool)returnedValue)
  {
      returnValue = (decimal)paramsArray[1];
  }
  else
  {
    returnValue = null;
  }

So first part is actually calling the method we now have:

  MethodInfo neededInfo = GetCorrectMethodInfo(typeof(decimal));
  decimal output = new decimal();
  object[] paramsArray = new object[2] { numberToConvert, output };
  object returnedValue = neededInfo.Invoke(returnValue, paramsArray);

So basically you take the variables, put them into an array, and then pass that array trough the invoke method. Nice thing is when the two variables are sent into the method, you don’t have to flag output as an Out parameter.

Now for the FINALLY ITS OVER

  if (returnedValue is bool && (bool)returnedValue)
  {
      returnValue = (decimal)paramsArray[1];
  }
  else
  {
    returnValue = null;
  }

You would think that the “output” variable you sent through .Invoke would hold the needed value. Too bad. You actually have to look at the object array passed in to get the value of the Out parameter. Kind of annoying, but deal with it.

And there you have it, how to not only find a methodInfo with an out parameter, but how to get the value back too. YAY

  using System;
  using System.Reflection;

My next post will show why I had to figure this out and I promise it will be worth it.

Linq Extension Methods Versus Linq Query Language… DEATHMATCH

Today I was writing out an example of why the extension methods are for the most part better to use than the querying language. Go figure I would find a case where that’s not entirely true. Say you are using these three funcs:

    Func<User, String> userName = user => user.UserName;
    Func<User, Boolean> userIDOverTen = user => user.UserID < 10;
    Func<User, Boolean> userIDUnderTen = user => user.UserID > 10;

As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let’s face it, the third should be pretty easy to understand now.

NOTE: This is a silly example but it works.

    var userList =
      from user in userList
      where userIDOverTen(user)
      select userName;
Versus

    var otherList =
      userList
      .Where(IDIsBelowNumber)
      .Select(userName)

In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can’t since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user:

    private Boolean IDIsBelowNumber(User user, Int32 someNumber, Boolean doSomething)
    {
      return user.UserID < someNumber;
    }

Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example.

Now if you look at the Linq query:

    var completeList =
      from user in userList
      where userIDOverTen(user, 10)
      select userName;

You’re good for it. Now the Extension Method:

    var otherList =
      userList
      .Where(IDIsBelowNumber????)
      .Select(userName)

Without a lambda expression, I really can’t call that method. So now what I have to do is create a method that creates a Func based off the original method call.

    private Func<User, Boolean> IDIsBelowNumberFunc(Int32 number)
    {
      return user => IDIsBelowNumber(user, number, true);
    }

And then plug it in:

    var otherList =
      userList
      .Where(IDIsBelowNumberFunc(10))
      .Select(userName)

What does this all mean? You just lost 5 minutes of your life. I hope it was worth it.

Change Target Framework on a Class Library (Visual Studios 2008)

Ok so this is a quick one but annoys the hell of of me.

Basically I am working with a 2.0 class library project and I wanted to use Linq. Now you would think when you “upgrade” the project to 3.5 using the wizard, the target framework would follow. Well, you are stupid. Now for web projects it seems you can look at the properties -> build and boom you can see it bright as day. Try doing this with a class library you and got nothin’.

Here’s the solution:

Goto the project properties -> compile -> Advanced Compile Options AND YOU WILL BE VICTORY!!11

So easy even a child could do it… after an hour of searching on google…

Cannot Resolve Method, Can’t Infer Return Type, and Funcs

So ran into this today and the answer was actually a lot easier to understand than I thought it would be.

Say you want to order a list of objects by a number. Seems simple. Now if you have been paying attention you would know I like using Funcs.

  Func<SomeClass, Int32> orderByNumber =
    currentClass =>  currentClass.SomeNumber;

  anotherCollection = someCollection.OrderBy(orderByNumber);

Seems simple, but what if you wanted to use a method already defined in the class?

  private Int32 ReturnNumber(SomeClass currentClass)
  {
    return currentClass.SomeNumber;
  }

It seems like this could be the way to go, right?

  someCollection.OrderBy(ReturnNumber);

Compile and BOOOOOOM you get an error. It says it can’t infer the return type of the method. Wait what? It’s pretty obvious right, it’s an integer. It had no problem inferring from the Func and you have to figure that the method itself is “typed” also. Well here’s the problem (And you’re dumb for not knowing this, but I’m not because I’m immune to dumb), ReturnNumber isn’t a method, it’s part of a method group. You can have a million (well maybe not that many) methods named ReturnNumber, all with different parameters. Why is this a problem? Well let’s use lambda expressions:

  someCollection.OrderBy(currentClass =>  currentClass.SomeNumber);

At this point it knows two things: currentClass is a SomeClass and there is a Method that takes in a SomeClass and returns something. So with that in mind, it looks for such a method and finds the return type. This is no different with the Func since the Func is basically unique due to it being a named field. After all you can’t have two fields named orderByNumber, but you can have many methods named ReturnNumber. That is where the problem is. When you use the second example:

  someCollection.OrderBy(ReturnNumber);

It can infer the SomeClass from the list and it sees the method. For there it has to find the method’s return type. Wait, which method? If i Have 10 overloads, each with different return types, how does it know what type to use? Well the answers is, it doesn’t. So basically you’re screwed. Sucks, huh?

Side note: This works

  Func<SomeClass, Int32> orderByNumber = ReturnNumber;

Skins in ASP.Net and how behind I am

So something that has been around for while that I just stumbled upon is Skinning. Basically, this allows you to sent a certain look (using style sheets) for every control in the site. This even includes the built in controls like Tables and Textboxes. How is this done? Well maybe I can tell you.

First you have to go to your project and right click (yes I could make images, but honestly that’s more work than needed.) the project itself. Add -> Add Asp.net Folder -> Theme.

Yay, you have a folder. Sweet. Now you actually have to add the skin itself. Guess what you have to right click? Yes, the new folder. Add -> New Item -> Skin File. Name it whatever (I say you call it Basic because that’s what I called it for this example) and open it up.

Now you have to create a .css file, if you don’t already have one, and for this example let’s say you make one called SkinMe.css. Now you get to add these meaningless classes:

.defaultTable
{
    width:500px;
    border-color:Black;
    border-style:solid;
    border-width:thin;
}

.defaultTable tr
{
    width:500px;
    background-color:Navy;
}

.defaultTable td
{
    color:Red;
}

.nonDefaultTable
{
    width:300px;
    border-color:Black;
    border-style:dotted;
    border-width:thick;
}

.nonDefaultTable tr
{
    width:500px;
    background-color:Navy;
}

.nonDefaultTable td
{
    color:Red;
}

Basically, I have two different classes for tables, with really only one difference. (border-style:dotted) Now you need that actual markup file to hold these wonderful tables:

    <asp:Table ID="tableSkinDefault" runat="server">
        <asp:TableRow ID="tableRowSkinDefault" runat="server" >
            <asp:TableCell ID="tableCellSkinDefault" runat="server" >
                hihihi
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

    <asp:Table ID="tableNonDefault" runat="server" SkinID="nonDefaultSkin" >
        <asp:TableRow ID="tableRowNonDefault" runat="server" >
            <asp:TableCell ID="tableCellNonDefault" runat="server" >
                hihihi
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

Now you might notice that the second table is using the SkinID tag. This will make sense in the next part. Have your skin file open? Gooood. Now just paste this into it:

    <asp:Table runat="server" CssClass="defaultTable" />
    <asp:Table runat="server" CssClass="nonDefaultTable" SkinId="nonDefaultSkin" />

Now it might be making more sense. Once I added the SkinId tag to the skin file, this allowed me to have the same control take on two different classes. Now, you can only have one default (The first one as it doesn’t have the SkinId tag) and any others for the same control have to use the SkinId tag.

Now go back to the two tables and once again you’ll see there is one with a SkinId tag and one without. The one without will take the default look and the one with will take the named look. Pretty simple, right? Well we’re not completely done yet. Two more small steps:

Be sure to remember to link the style sheet on the page with the tables:

    <link href="../CSS/SkinMe.css" type="text/css" rel="stylesheet" />

And you have find the “pages” section of the web.config and add a tag:

    <pages styleSheetTheme="Basic">

And now you have the ability to set every table’s class in the entire site. Best thing is, this can be used for other properties too. Say you have a name property on some usercontrol (We’ll call it MapControl). You can do this:

    <%@ Register Assembly="Some.Control.Assembly" Namespace="Some.Control.Assembly.Controls" TagPrefix="someControl" %>

    <someControl:MapControl Name="Hi" />

And now every MapControl will have the Name property set to “hi”. Kind of nice.

Another removing Lambda “trick”

And by trick, I mean I was too slow to realize that:

  someDictionary.Add("Hi", (Boolean doThis) => SomeMethod(doThis));

Can be done this way:

  someDictionary.Add("Hi", SomeMethod);

Where the dictionary is:

  Dictionary<String, Action<Bool>> someDictionary;
  someDictionary = new Dictionary<String, Action<Bool>>();

And SomeMethod is:

void SomeMethod(Boolean doSomething)
{
  //Something is to be done!
}

Which as far as I know, removes a step from the whole process. What does that mean? Well if you break the first one down into an anonymous method, it would look like this:

  someDictionary.Add("Hi", delegate(Boolean doThis){ SomeMethod(doThis); });

I am assuming this would create a reference to a completely new method as opposed to the second example which just uses the already existing method’s reference. Fun yah?