h1

Object Initialization in C# 3.0

February 19, 2008

In older versions of C# when you create a new object and had to initialize some of its members, you had to write code similar to this -

Name name = new Name();
name.FirstName = “Fred”;
name.LastName = “Nurk”;

To make this sort of initialization easier, C# 3.0 introduces new syntax as shown below -

//Initialization with empty constructor
Name name = new Name
             { FirstName = “Fred”,
               LastName = “Nurk” 
             };

The syntax also allows constructors with parameters -

//Intialization with constructor parameter
Name name = new Name(someParameter)
            {
                FirstName = “Fred”,
                LastName = “Nurk” 
            };

You can also do nested initialization as shown below -

//Nested initialization
Customer customer = new Customer
{
    CustomerName = new Name 
       { FirstName = “Fred” },
       Address = “400, Somwhere”
};

The syntax is pretty straight forward. You can initialize any public Property or member variable, by specifying the name of the Property/variable and initializing it with a = operator. More than one member can be initialized by using the comma operator. The only thing you cannot do is call a method or initialize a private member inside the initializer.

h1

IE Style Tabs in Html

February 13, 2008

Lot of web applications I’ve worked with have some kind of navigation that is implemented as Tabs. When I first started using tabs in Web Apps, I implemented them in tables, with the left hand side image of the tab in one cell, the middle part in another cell and the right hand side of the tab image in another cell.

That was before I discovered the beauty of CSS. The last few years I have been evangelising table-less design to every project/client that I go to and pretty much wherever I go, I take my “Tab” design with me. I cannot claim any originality to it, though. I first read about the Sliding door technique at “A LIST apart” a few years ago and I’ve been using it ever since.

Here is my implementation of it that resembles the IE 7.0 style tabs.

image

To do this, I created 6 images -

Image Description
tab-background tab-background.png: The background on which the tabs are present
tab-left tab-left.png: The left side of an unselected tab
tab-right tab-right.png: The right side of an unselected tab
current-tab-left current-tab-left.png: The left side of the selected tab
current-tab-right current-tab-right.png: The right side of the selected tab
hover-tab hover-tab.png: The image when you hover the mouse over the tab

The html markup used to define the tabs is a very simple unordered list -


<div id="primaryNavigation">
    <li><a href="#">Tab One</a></li>
    <li id="current"><a href="#">Tab Two</a></li>
    <li><a href="#">Tab Three</a></li>

    <li><a href="#">Tab Four</a></li>

</div>

The markup is simple, because all the presentation information is present in the css file:


body
{
    background:#fff;
    margin:0;
    padding:0;
    color:#000;
    font:10pt Tahoma, Helvetica, sans-serif;
}
#primaryNavigation {
  float:left;
  width:100%;
  background: url( 'Images/tab-background.png' )
		repeat-x 100% bottom;

}
#primaryNavigation ul {
    margin: 0;
    padding: 2px 10px 0px 3px;
    list-style: none;
    height: 36px;
}
#primaryNavigation li {
    float: left;
    background: url('Images/tab-left.png' )
		no-repeat left top;
    padding: 0px 0px 0px 3px;
    height: 36px;
}
#primaryNavigation a {
    float: left;
    background: url('Images/tab-right.png' )
                no-repeat right top;
    padding: 6px 15px 0px 6px;
    text-decoration: none;
    color: black;
    white-space: nowrap;
    height: 36px;
}
#primaryNavigation a:hover {
    color: black;
    background: url('Images/hover-tab.png' )
                no-repeat right top;
  }
#primaryNavigation #current {
    background:url('Images/current-tab-left.png' )
		no-repeat left top;
    float: left;
    margin: 0;
    padding: 0px 0px 0px 2px;
    height: 36px;
  }
#primaryNavigation #current a {
    background-image: url('Images/current-tab-right.png' );
    color: black;
    white-space: nowrap;
    height: 36px;
    padding: 6px 15px 0px 6px;
}

Pretty simple, huh? This should work in most browsers, although I’ve tested in only on ID 7.0.

h1

Type inference/Implicitly Typed local variables

February 11, 2008

One of the new features in C# 3.0 is Implicitly Typed local variables. In scripting languages like JavaScript, you can define a variable like this -

var x = “some value”;

You can now do the same thing with C# 3.0 and although some people may consider this feature to be nothing more than syntactic sugar or a declaration shortcut  for lazy programmers, it is needed for declaring anonymous types and while using LINQ (which I’ll cover in future posts).

C# uses type inference to automatically detect the type specified on the right hand side of the declaration. So, all these declarations are valid:

var myName = “Mahesh Krishnan”;
var myHeightInCms = 182;
var myWeightInKgs = 76.432;
var myPet = new Cat();
var dict = new Dictionary<int, string>();

var b = (ans == “Y“) ? true : false; 

The main rule is that the variable has to be declared in one statement as shown above. Under the covers, C# substitutes  var with a string or an int or whatever type is specified on the right hand side of the declaration. This is done at compile time and as a result type safety is not compromised. When you use Visual Studio 2008, you will also notice that intellisense works correctly for the type used.

You cannot have an empty or null declaration

The C# compiler needs to know the type of variable it is creating. So an empty variable declaration or a variable declaration that is assigned to null is not allowed.

//Neither statements are valid
//
var uninitalized;

//var x = null;

Once a variable has been assigned, you cannot re-assign it to another type

In languages like JavaScript, you can assign an object to a variable and then re-assign another object of a different type to it. But in C#, this is not legal.

var myBooleanValue = true;           

//Cannot change types!
//myBooleanValue = “false”;

You cannot mix and match types

//Not allowed
var x = (myBooleanValue) ? true : “false”;

As I mentioned earlier, type inference is done during compile time and a statement as shown above is not supported as the type of x can only be determined at run time. As a result, this statement is not valid.

You cannot create an array of vars

Creating an array of var as shown below is not allowed:

//Not valid
//var[] arr = new int[] { 10, 20, 30 };

You can still assign an array to an array variable declared as a var as shown below -

 var arr = new int[] { 10, 20, 30 };

I will cover implicitly typed arrays in a later post.

Can only be used for local variables

One other major rule is that you cannot use var to declare member variables in a class. They are only allowed within a function body.

Use them wisely

Although, using var to declare a variable is a nice feature, use it wisely. Using it to declare known types such as integers and strings can make the code a bit unreadable. Another thing to avoid is using the keyword var as a variable. This is still allowed for backward compatibility, but you should avoid it at all costs.

(This is my second post on the new C# features. My first post on Property short cuts can be found here)

h1

Property shortcuts in C# 3.0

February 9, 2008

I gave a talk about the new features in C# 3.0 at the Victoria .NET Dev SIG back in December. It was a packed house, with over 100 people and the turn out surprised me considering the fact that it was less than 10 days to Christmas.

Anyway, I had promised I would post my examples to the attendees and one of them asked about it recently. So, I decided to get my act together and blog about it.

Changes to C# 3.0 include features that range from what people refer to as syntactic sugar to some really cool stuff that you can do with LINQ. And covering them all in one post will get too big (for me). So, I’ll do one feature at a time, starting with Property Shortcuts.

Property shortcuts

Typically in C# 2.0, you would implement a property as shown below -

private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value;}
}

It is a good thing to encapsulate your private data members, but more times than not, you will find yourself creating a wrapper for your private data members and nothing more. So, why not just expose these data members as public? Because, that would be bad practice - we would then lose the flexibility to change the implementation later.

C# 3.0 provides us with a compromise. You can now declare your property as shown below -

public string FirstName { get; set; }

By declaring it this way, there is no need to explicitly create a private data member to hold FirstName. So, you may ask - what is the difference between this and declaring the data member FirstName as public? The difference is that under the covers, C# creates a private data member for you. And if you decide to change the implementation later,  you can.

If you think that the declaration of FirstName is very similar to how you would declare it in an interface, you would be right. Declaration of FirstName in an interface will still look like this -

interface IName
{
    string FirstName { get; set; }
}

And if you wanted to declare this in an abstract class, then you can still do it -

abstract class AbstractName : IName
{
    public abstract string FirstName
        { get; set; }
}

Using the abstract keyword prevents the compiler from generating private data member for the property.

Is the old syntax supported? Absolutely. The only thing that will not work is a syntax that goes something like this -

// Will not work!
public string MyProperty { get; }

The reason for that is quite obvious, actually. If this syntax was indeed legal, how would you assign a value to the property? You can’t and because there is no explicit private data member, you cannot assign a value to that either. For the same reason, using a set; in isolation will also not work.

h1

Reporting Services: Best practices and tips

October 20, 2007

As a follow up to my talk on Reporting Services, here are some links to Reporting services tips and best practices -

And here is Greg Low’s podcast on SQL Down Under with Adam Cogan on the topic.

h1

Reporting Services Tips and Tricks

October 14, 2007

Here is the link to the presentation I gave at Wagga Wagga. During the presentation I promised to upload a few relevant links. I’ll be doing the uploads in a couple of days, so watch this space…

h1

Presenting at SQL Down under Code Camp 2007

September 13, 2007

I will be presenting on SQL Server Reporting Services: Tips and Tricks at the SQL Down Under Code Camp in Wagga Wagga. My talk is on at 11:30 on Saturday the 13th of Oct. I’ll post the slide deck after the talk. Watch this space.

h1

Acropolis

August 9, 2007

I have to admit that one of the presentations I wish I hadn’t attended at Tech.Ed was the one on Acropolis. Maybe it wasn’t presented properly or maybe it is still early days for the product or maybe I just didn’t get it. The Apps created using Acropolis looks pretty cool but how you do it leaves a lot to be decided. Kathy Kam built a RSS reader using Acropolis and made changes to it to show how easily the UI could be changed, but I am not convinced yet…

h1

Software Factories

August 9, 2007

Tom spoke about the major Software factories that are in use now -

  • Web Client Software Factory
  • Web Services Software Factory
  • Smart client Software Factory
  • Mobile Client Software Factory

He gave a demo on the current Web Service Software Factory and also the yet to be released newer version of it. The new version is an interesting one, as you first define the model using DSL and then let the Software factory generate the code after that. I actually like this approach, but Darren got me thinking about the frequency at which the p&p team make breaking changes. All the guidance automation that people would have built/extended using the old Service Software factory would now be rendered redundant. Not a very good thought for people who would have done that.

Having said that I have to admit I am looking forward to playing around with the new “Modeling edition” Service Factory.

h1

EntLib 3.1

August 9, 2007

There are people who love EntLib and people who hate it. I would like to see myself somewhere in the middle. At Tech Ed today, Tom Hollander presented on EntLib 3.1 - he did not cover on the usual Application blocks that exist for Exception handling, logging, data access etc and instead concentrated on the two new ones - Validation Application Block and Policy Injection Application block.

The key areas that he covered in his presentation were -

  • How the Validation Application Block can be used to specify validation either using Attributes, programmatically or even in the configuration. He also spoke about how it is integrates nicely with ASP .NET, Win Forms and WCF
  • The Validation App Block contains rules to do the most common validations such as Null checking, Range checking, Validation using regular expressions, checking for characters and date lengths, property conversions, etc
  • How the Policy Injection Application block can be used for separating cross-cutting concerns from business logic