Home > Visual Studio > Visual Studio 2008 Class Diagram

Visual Studio 2008 Class Diagram

November 29, 2007

I’ll be returning to my series on “Upgrading your C# skills” next week. For now, though, I wanted to share with you a cool new option in VS2008: Class Diagrams.

Class Diagrams

A Class Diagram is a new file type that allows you to visually create, edit, and manage Classes, Structs, Enums, Interfaces, Delegates, and more. It is a quick and easy way to add Property and Method stubs to existing Classes or to create entire class shells. You can even manage Events and Fields. The interface is immediately familiar and intuitive. Diagrams can even be exported to Images.

To begin, open a project in Visual Studio and follow these steps:

  • In the Solution Explorer window, right click the project and select “Add -> New Item”.
  • From the Add New Item dialog box, highlight “Class Diagram” and give it a name.
  • Press the Add button. The Class Diagram file will be added to your project and the designer will open.

You will now have a Blank Diagram to work with in the designer. To add an existing class to the diagram, simply drag and drop it from the Solution Explorer window onto the design surface. To create a new Class (or Struct, Enum, etc.), right click in the designer and expand the “Add ->” menu item. Select the appropriate type and follow the instructions. Easy as pie.

Once you have an item in the designer, it will look something like this (Click on Screen Shot for Full Size):

Class Diagram Screenshot

I moved the Class Details window to the right, but the default will have it on the bottom. Just like working with a Control in a Form, you will need to select the class in the designer window in order for its details to show in the Class Detail window. And you can have multiple classes in a diagram.

When you create a new item, you will be prompted to either create a new file or append to an existing file. As you can see, the Class Detail window allows you to easily add Methods, Properties, Fields, and Events to a class. You can edit the Name of an element, the Type, the Access Modifier, and the Summary. The Summary column is the XML Comments description: if you leave it blank, then there will be no XML comments at all. If you supply a Summary, it will be added to the source code. You can also elect to “Hide” an element, which only means that it will be not listed in the Class Diagram itself.

So let’s talk about what code the IDE generates from this designer. Consider the Person class listed above: this class already existed and was dropped into the Class Diagram designer. I then added the DOB, MaritalStatus, and IsMilitaryVeteran properties using the Class Detail window. Now the code looks like this:

class Person
{
    public Person()
    {

    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    /// 
    /// Date Of Birth
    /// 
    public string DOB
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Marital Status Code
    /// 
    public char MaritalStatus
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Exposes whether or not this Person ever served in the Armed Forces
    /// 
    public bool IsMilitaryVeteran
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }
}

The properties were created, but not as I would have expected. I would have expected these to be default Automatic Property stubs. Instead, they are classic property stubs, and the getter throws a NotImplementedException. The good news is that this will compile as is. The bad news is that it is surely not the behavior you want, so you will have to do some work to implement the details. And you cannot simply remove the NotImplementedException because the getter must have a return path. Of course, a simple copy and paste can quickly convert these to Automatic Properties, but it is unfortunate that this isn’t the default behavior.

Which brings up another good point: the Property is created, but with no corresponding variable, and yet it still compiles. This tells me that the Automatic Property mechanism is still in play here, but it causes a problem when you go to implement the details: there is no variable to return, so you must create one. A pretty minor point, but worth noting none-the-less. And again, I think this issue could have been avoided if the standard Automatic Property stub had been implemented (or at least optional).

So let’s make this a little more robust and add some other goodies. First, since I have to implement the details anyway, I’m going to add fields to support my new properties. Next, I’m going to add a GetFullName method, and I’m going to override the ToString method. Finally, I’m going to add a MaritalStatusChangedEvent Event Handler. Now let’s look at the results:

class Person
{
    private string _dob;
    private bool _isMilitaryVeteran;
    private char _maritalStatus;

    public event EventHandler MaritalStatusChangedEvent;

    public Person()
    {

    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    /// 
    /// Date Of Birth
    /// 
    public string DOB
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Marital Status Code
    /// 
    public char MaritalStatus
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Exposes whether or not this Person ever served in the Armed Forces
    /// 
    public bool IsMilitaryVeteran
    {
        get
        {
            throw new System.NotImplementedException();
        }
        set
        {
        }
    }

    /// 
    /// Retrieves the Full Name of the Person formatted as "Last, First".
    /// 
    public string GetFullName()
    {
        throw new System.NotImplementedException();
    }

    public string ToString()
    {
        throw new System.NotImplementedException();
    }
}

Much as expected, the fields are simple fields, the Event is declared, and the methods are stubbed but all throw a NotImplementedException. This all compiles right out of the box, but if you want to really override ToString(), you’ll need to add the keyword yourself. Again, it would be nice if the tool detected that for you and prompted you to select the desired behavior, but it is not that big of a deal.

Finally, the Class Diagram tool has some options. When you open one, VS2008 will include a new Menu and a new Toolbar. Explore these options a little and you’ll find some other helpful items. In this last screen shot, representing the completed class above, I have elected to show full signature detail in the Designer. (Click on Screen Shot for Full Size).

Class Diagram Screenshot

So I encourage you to explore this feature. For rapid stubbing, I think you’ll find this a very handy and useful tool.

Advertisements
Categories: Visual Studio
  1. Clayton
    June 18, 2008 at 11:35 pm

    fyi… Class Diagrams were introduced in VS2005, not VS2008

  2. June 19, 2008 at 8:06 am

    Thanks, I obviously wasn’t aware of them. Do they function the same way?

  3. Nik Radford
    June 24, 2008 at 5:25 am

    Second, Properties don’t require backing fields, even if they are not automatic

    example, the below code is perfectly valid.

    string Hello
    {
    get
    {
    Console.WriteLine(“Lots of console output”);
    return String.Empty;
    }

    set
    {
    for (int i = 0; i < 10; i++)
    {
    Console.WriteLine(“Lots of console output”);
    }
    }
    }

    This is because when the property is invoked, the JIT compiler treats these as two seperate function

    string GetHello();
    void SetHello(string value);

    as opposed to a property in the sense we see them as.

  4. June 24, 2008 at 7:57 am

    Your point is completely valid. I was approaching it from the sense that the property represented a data variable of the Class, which correctly is not necessarily required. Again, I was addressing what I thought the default behavior should be (or at least what I would prefer it to be). While the example you gave is legitimate and will function, it certainly is not a style I would endorse.

    Thanks

  5. Alex da Ukrainian
    September 30, 2008 at 4:38 am

    Joel, your point about properties is valid. It is unfortunate that class designer isn’t using the automatic properties because it forces people to switch between designer and code to have working code.

    I think current implementation of Class Designer is relatively useless, but it does come in handy sometimes. So if you do use it, there is a free and lightweight PowerToy add-in to add some neat functionality to the designer, by the way, and it can be found here: http://www.codeplex.com/modeling. Check it out.

    Thanks for the blog!

  6. October 18, 2009 at 9:50 pm

    Class designer is well enhanced in Visual Studio 2010.

  7. Ayana
    March 11, 2010 at 2:24 pm

    I don’t seem to have a template for Class diagram. I go to the Solution Explorer and select to add a new item, but Class Diagram is not present in the list of templates. Do you know why?

  8. Sara
    April 29, 2010 at 10:23 am

    Ayana it is likely that you don’t have it in your version of Visual Studio. It seems that it is not available in all versions.

  9. Sidney LU
    December 22, 2010 at 4:49 am

    the most missing things is no search function,i can’t find my class if there are lots of classes

  10. bhargav
    May 17, 2011 at 6:20 am

    there is no such kind of option in my version to add class diagram does it need any extra file

  11. ccampbell
    June 14, 2011 at 2:13 pm

    Make sure to have a project selected, and not the entire solution.

    When I selected the solution, then went to Project -> Add New Item… I did not have a Class Diagram option in General.

    However, when I selected a project in my solution explorer and then went to Project -> Add New Item… -> General I did have a Class Diagram option.

  12. Alex
    June 30, 2011 at 1:57 pm

    Hi Joel,
    The properties are set up this way because that would be you’re starting point if you were using test driven development (TDD), first the class is made with stubs that all throw exceptions – then you make your test (all of which will fail) then the aim is to fill out your class (functions / properties etc) until all tests pass.
    Although i know lots of people don’t code this way i’d say it was the standard in most development environments – very good for making reliable code that you can refactor without the worry of side-effects.
    :p

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: