13
C# vs. Objective-C: If Spoiling
In Categories: Programming | No comments
I’m a pretty easy guy when it comes to programming languages. Nothing ever really bothers me too much about any particular feature of one. I don’t really get angry with a language unless it has some type of ridiculous white spacing constraints (I’m looking at you Python). I’ve never really worked in one single language too long so I don’t really think I’ve ever been spoiled on a particular feature of one. That is, until recently.
I have of late been doing a lot of Objective-C work. There are a ton of C#’ers that loathe the language and it’s Smalltalk-y quirks, but I myself have grown to enjoy it. So much so that it has been a bit harder to adjust when sitting down to work with C#. The self vs. this, method naming, etc etc., don’t make the Objective-C ‘off’ to C# ‘on’ switches very easy.
One thing that has drove me crazy as of late is C# not having built in null checking in ‘if’ statements. In Objective-C, if you want to check for null (nil) all you have to do is:
SomeSuperCoolModelObject* obj = [[SomeSuperCoolModelObject alloc] init];
if(obj) { NSLog(@"OMG this obj is not nil!!!!"); }
Or something like that. Not too shabby. I love this little feature of the language as it makes the code ‘feel’ cleaner. In C#, you would have to do the following:
SomeSuperCoolModelObject obj = new SomerSuperCoolModelObject();
if(obj != null) { System.Console.WriteLine(@"OMG this obj is not nil, I mean, null either!!!!!"); }
Meh. I can do without that. So, how do you go about making this Objective-C style if statement work in C#, you may ask? Well, it’s actually kinda easy, so I’m assuming it’s kind of dangerous.
I was working on a small one-off project at work and I figured I’d give it a shot. The key is in C# operator overloading abilities. In C# you can overload the true and false operators for an object. These operators dictate how a true/false expression request yields for the object i.e. in an ‘if-else’ scenerio. I added the following operator overloads for my object:
...
public static bool operator true(SomeSuperCoolModelObject obj)
{
return obj != null;
}
.....
public static bool operator false(SomeSuperCoolModelObject obj)
{
return obj == null;
}
These two operator overloads will now allow you to do the following:
SomeSuperCoolModelObject obj = new SomerSuperCoolModelObject();
if(obj) { System.Console.WriteLine(@"Ha, take that Objective-C!!!!!"); }
Now, is this something that is not without caveats? Of course not. You really need to think through your use of this. Think about where true is yielded in your scenarios and if this breaks the true/false for your given object take it out. It might not be worth it in your case. Remember that it can be found/used in other expressions/operators such as the ?: operator. For me, it helps me to NOT have to see all those squiggly lines in Visual Studio when I forgot to put ‘== null’ in an if statement. Hope this helps.
Cheers.