IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

Is String.IsNullOrEmpty Good or Bad?

I started to wonder about that when I was looking for an equivalent method in Ruby. Apparently, Ruby doesn’t come with such a method built-in, but you can add it very easily by using Ruyb’s monkey patching abilities.

This is odd, because Ruby is the greatest language and has everything you possibly need (and IronRuby is even better! :) ). So why isn’t there an IsNullOrEmpty-like method? Well, they might just didn’t think it was important enough. And there might be a different answer, maybe the decision has other reasons below the surface.

Several developers have discussed the String.IsNullOrEmpty issue over the years. Some say it’s good, some say it’s bad and some even say it’s hazardous to your code (because of a bug it has).

For me, I go with Ruby’s approach (unless they didn’t add it because of time constraints). Most of the time there will be a big difference between a null string object and an empty string object. Therefore, I think that String.IsNullOrEmpty() should be avoided as much as possible and the application should have a convention of how uninitialized strings should look like – nulls or String.Empty

For example, say you need to validate some input and String.Empty is sent to you. How do you know if the string is an uninitialized string or a real input? saying that null is the convention would have solved this confusion.

I know there are cases where you have to use IsNullOrEmpty. For example, when using 3rd party components that you are not aware of their uninitialized string convention (if such exists…). This is why I don’t rule out IsNullOrEmpty entirely. I do say that wherever you can, do not use it and prefer str == null to spot uninitialized strings.

By the way, deciding that only null is the convention for uninitialized strings can also improve your application performance since str == null is faster than String.IsNullOrEmpty(str) in about 35%. However, you’ll notice an improvement only if you’re doing billions of String.IsNullOrEmpty calls, so don’t panic right away.

In conclusion, String.IsNullOrEmpty is there for convenience reasons.  Sometimes with convenience comes tranquility, so make use of it wisely!

Just a final addition, Ruby on Rails adds a blank? method to Ruby which provides the equivalent to String.IsNullOrEmpty method in C#. So, if Ruby does not contain everything you need, Ruby on Rails surely does! :)

So what do you think, IsNullOrEmpty is good or bad for your application?

All the best,
Shay.

kick it on DotNetKicks.com Shout it



 

C# Recorder using IronRuby

[This post is the second in my series of IronRuby samples. Read the first one here]

The release of Visual Studio 2010 Beta 2 and IronRuby .Net 4.0 Beta 2 CTP has brought some AMAZING abilities to the .Net world like the dynamic keyword. This keyword is a revolutionary little thing. It takes everything you know about C# and throws it away – explicit types, locating syntax errors in compilation time, compiled code…

Sounds bad? well, it is just AWESOME!!! The dynamic keyword brings so much goodness to our beloved C# language, that if it was possible I would have hugged it and asked it to join my family.

Well, enough with the nonsense, let’s get down to business. IronRuby is Microsoft’s implementation of the Ruby language. It runs on top of the DLR and provides a seamless integration with .Net code. In short, it ROCKZZZZZ. This post is about IronRuby’s seamless integration with .Net and the ability to use the great power of Ruby inside C#.

The Ruby language has some very powerful metaprogramming abilities. One of those is the method_missing method. When you declare it in your class, every call to a method that doesn’t exist will be routed to it. You can then do whatever you want with the call – execute a different method, raise an exception, interpret the call somehow or just do whatever you want (jump in the air? do your little Irish dance thing?).

Another nice metaprogramming feature is the ability to send requests to objects by using the send method. The concept is very similar to C#’s reflection method – Invoke.

Now if we combine method_missing and send, we can create a class that saves calls and playbacks them upon request. I will call it… tam tam tam… Recorder:

 

class Recorder
  # Initialize an array that will save the calls
  def initialize
    @calls = []
  end
   
  # Save the calls to method_missing	
  def method_missing(name, *args, &block)
    @calls << [name, args, block]
  end

  # Playback the calls on a given object	
  def playback(obj)
    @calls.each do |name, args, block|
      obj.send name, *args, &block
    end
  end
end

 

I think this code is pretty straight forward, no special things here. With this class defined, we can record Ruby calls and playback them on Ruby objects:

 

# Record calls
rec = Recorder.new
rec.reverse!
rec.insert 2, "ABAB"
rec.delete! "A"

# Playback them on a real object
str = "Hello World"
rec.playback(str)
puts str # Prints "dlBBroW olleH" 

 

 

It is AWESOME, but the great thing about it is that with .Net 4.0 and the dynamic keyword, it is available in C# too!

To try the next code by yourself, first open Visual Studio 2010 Beta 2, create a new C# console application and add references to IronRuby.dll, IronRuby.Libraries.dll, Microsoft.Scripting.dll and Microsoft.Dynamic.dll (remember to use the CTP assemblies and not the regular IronRuby assemblies).

The following code loads the Ruby recorder class file (recorder.rb) to the C# environment, creates an instance of the Recorder class, records a few operations and playbacks them on .Net objects:

 

static void Main(string[] args) 
{      
  // Load the recorder IronRuby file
  var engine = IronRuby.Ruby.CreateEngine();
  engine.ExecuteFile("../../recorder.rb");
  dynamic ruby = engine.Runtime.Globals;

  // Initialize IronRuby's recorder class
  dynamic recorder = ruby.Recorder.@new();

  // Record
  recorder.Add(1);
  recorder.Add(2);

  // Playback on CLR's List object
  List<int> list = new List<int>();
  recorder.playback(list);

  // Print the results!
  foreach (var item in list)
  {
    Console.WriteLine(item);
  }

  // Record console printing
  recorder = ruby.Recorder.@new();
  recorder.Write("IronRuby");
  recorder.WriteLine(" and .Net 4.0");
  recorder.WriteLine("Rock!!!!!!!!!!");

  // Playback on console
  recorder.playback(Console.Out);
}


The output to the console will be:
1
2
IronRuby and .Net 4.0
Rock!!!!!!!!!!

Try it out and see the magic happens right in front of your very own eyes!

In my opinion, this joint venture is incredibly helpful and useful. I predict that as time goes by we will see more and more dynamic language code make its way to the conservative .Net world, enhancing it and adding it powerful abilities that it never has had before.

All the best,
Shay.

Share it: kick it on DotNetKicks.com Shout it



Visual Studio Tip: Compilation Symbols

There are times when we need to use different code statements for different build configurations – this means that some code will not exist in assemblies that are built in certain build configurations.

Compilation symbols come to help in this case. You can set a symbol that will exist in  a specific build configuration and then use it inside your code files to write or exclude code when this project is built using this build configuration.

The most familiar case of this scenario is debug and release build configurations. Actually, the debug build configurations comes with a compilation symbol by default named DEBUG. By using it you can write code that will run only when you compile your project in debug mode (show extra message boxes, write more logs, etc.).

Creating Compilation Symbols

  1. In Visual Studio, go to Project-> <project name> Properties…
  2. The project properties view will open. Click on “Build” on the left.
  3. The Build settings will open on the right. The first field there, with the label “Conditional compilation symbols” is the one you need.
  4. Add there the name or names (semi-colon separated) of the compilation symbols you want to define. Pay attention that the naming convention for these symbols is all uppercase.
  5. Save

You’re done. You can start using the compilation symbols you have just  defined. The next screenshot contains a sample project with two symbols defined – SHAY and FRIEDMAN:

IronShay | Compilation Symbols

Using Compilation Symbols

In order to use the compilation symbols you have defined, you need to use the special compilation conditions. If these conditions are not met, the code within the condition will not be compiled at all.

The condition starts with #if <condition> and ends with #endif. For example, the next code will be compiled only when SHAY is defined (which is in debug build configuration):

#if SHAY

Console.WriteLine("SHAY is defined! woot!");

#endif

You can also write more complicated conditions like !SHAY for all build configuration without SHAY defined. You can add conditions too – SHAY && FRIEDMAN.

Well, that’s about it!
Hope it helps,
Shay.

kick it on DotNetKicks.com

The dynamic Keyword Part 2 – IDynamicObject

This is the second part of my series about the new dynamic keyword in C# 4 (Read the first post here).

As I talked on the first post, the dynamic keyword does the dirty reflection work for you. This is very nice, but it’s like moving forward from a desktop computer to a 10kg laptop – you get to be more dynamic, but it’s still heavy to move around…

The first laptop - heavy!

The dynamic keyword holds a greater power inside, and this is what I’m going to talk about today – the IDynamicObject interface.

What is the IDynamicObject interface?

When we declare an object as dynamic and execute actions upon it, we actually use a default IDynamicObject implementation.

The IDynamicObject interface has a few methods, the important ones (for this post) are – Invoke, GetMember and SetMember.
The idea is very simple -

dynamic myObject = GetIDynamicObject();
myObject.SomeProperty = "Hello"; // This calls IDynamicObject.SetMember
Console.WriteLine(myObject.SomeProperty); // This calls IDynamicObject.GetMember
myObject.RunSomething(); // This calls IDynamicObject.Invoke

This means that we can implement our own behavior for the dynamic invocation! let’s see what we can do with that…

What can I do with that?

If we implement our own IDynamicObject, we can ease the pain of various daily operations. For example, we can develop an IDynamicObject that will give us the ability to use un-typed datasets as if they were typed. Another example can be an implementation that will enable us to dot through an xml file, with no need of XmlDocument, xpath and their friends. I’m sure there are tons of other uses that can and will be implemented.

Sample IDynamicObject implementation – Working with un-typed datasets

The first thing we’ll do is to create an extension method to the System.Data.DataSet class:

public static class Extensions
{
public static dynamic AsDynamic(this DataSet dataSet)
{
return new DataSetDynamicCaller(dataSet);
}
}
When we call DataSet.AsDynamic(), we’ll receive a DataSetDynamicCaller class in return, as a dynamic type object. 

Now what we need to do, is to generate classes that dynamically access the dataset objects. This is a very easy process as you will see in just a moment.

So let’s create the DataSetDynamicCaller class:

public class DataSetDynamicCaller : DynamicObject
{
DataSet dataset;

public DataSetDynamicCaller(DataSet dataset)
{
this.dataset = dataset;
}

public override object GetMember(System.Scripting.Actions.GetMemberAction info)
{
return new dataset.Tables[info.Name];
}
}

This is it… Now to the explanation…

Firstly, I inherit from DynamicObject – this is the basic implementation to the IDynamicObject interface (download link is at the end of the post). As I understand, the DynamicObject class will be a part of the System.Dynamic namespace in C# 4, so you won’t need this file on the final version. I won’t deep dive into this implementation, it’s a subject to another post.

Secondly, The DataSetDynamicCaller class is very simple – we get the untyped dataset in the constructor and save it in a private member. Then, whenever the user asks for a property, we return a DataTable that matches the name of the requested member.
This will give us the ability to call a table directly. For example:

DataSet ds = new DataSet();
ds.Tables.Add("MyTable");

dynamic dynDS = ds.AsDynamic();

DataTable tbl = dynDS.MyTable; // This will work!

It’s as simple as that!

I attach the class I’ve written (the link is at the end of the post). The sample contains two more classes and enables you to use the un-typed dataset even more easily. For instance, calling dynDS.MyTable.GetRow(0).MyColumn will return the value of the MyColumn column from the first row of the MyTable table…

In conclusion, the IDynamicObject interface opens a large amount of possibilities for improving our everyday work in a lot of aspects. It starts from accessing untyped datasets as if they were typed and ends where your imaginations does. This is what they mean when they say dynamic capabilities!

image

Downloads:
DynamicObject.cs
DynamicDataSet.cs

All the best,
Shay.

kick it on DotNetKicks.com
Shout it

The dynamic Keyword Part 1 - Introduction

Firstly, in order to use the dynamic keyword, you'll have to download the VS2010 VPC image and work there. There is no way currently, to download and install Visual Studio 2010 on your local computer.

Now we're ready to explore the future!

So what is the dynamic keyword?

The dynamic keyword is a new type of variable that will be added to the syntax of C# 4.0. Behind the scenes, the dynamic keyword is declared as an object with an attribute that indicates that this is a "special" object that should be treated dynamically.

The way you declare it is just like any other variable type:

dynamic myDynamicVariable = something;

What is it good for?

This dynamic mechanism is a wonderful thing for a bunch of different things that now we have trouble with. Things like - reflection in different environments, calling dynamic languages, dynamic fluent interfaces and more. All of these will become tremendously easier, using the dynamic keyword.

Example - Reflection using dynamic

Let's say I have a type that I define on one class library, I'll call it TheMysteriousType. This is its code:

namespace Mysterious
{
public class TheMysteriousType
{
public string RevealYourSecrets()
{
return "Never!";
}
}
}

Now, I'll create another class library with a method that receives a dynamic variable and executes the RevealYourSecrets method:

namespace Revealer
{
public class Revealer
{
public static void RevealSecrets(dynamic obj)
{
Console.WriteLine("Reveal you secrets, object! {0}", obj.RevealYourSecrets());
}
}
}

And last thing - I'll create a console application that has the above 2 class libraries references. It will contain the following code:

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Mysterious.TheMysteriousType myst = new Mysterious.TheMysteriousType();
Revealer.Revealer.RevealSecrets(myst);
}
}
}

The flow of the application goes like this:

  1. myst variable is created.
  2. Revealer.RevealSecrets gets the myst variable as dynamic.
  3. Inside Revealer.RevealSecrets: obj.RevelarYourSecrets() will generate a dynamic invocation of the RevealYourSecrets method. Behind the curtains, this will end up running the traditional reflection code for us.
  4. The application ends up writing to the screen: "Reveal your secrets, object! Never!".

This is a sample reflection scenario - the Revealer class does not know the object it receives. In order to invoke the RevealYourSecrets method prior to C# 4, we had to use some complicated reflection code. From C# 4, we'll have the dynamic keyword on our side that will do that for us.

This is great because it saves us time and make our code more readable, eventually making it easier to maintain.

Stay tuned to the next parts!
Happy Holidays!
Shay.

kick it on DotNetKicks.com