Home > .NET 3.5, C# 3.0 > Automatic Properties and StackOverflowException

Automatic Properties and StackOverflowException

January 14, 2008

I’ve written a couple of times before about Automatic Properties, a tiny little feature that I have really come to enjoy. Remember that an Automatic Property looks something like this:

// An Automatic Property
public string FirstName { get; set; }

I’ve also written that if you want to add any behavior to this property, then you must create a variable and complete the code just as you would have a regular property. I was coding the other day and I had to transform add some behavior to what had been an automatic property. For grins, I wanted to see what I could get away with, so I tried a couple of different approaches.

First, I really only wanted to add behavior to the Setter, so I tried leaving the Getter as is:

// Will not compile
public string FirstName
{
    get;
    set
    {
        FirstName = value.TrimEnd(new char[] { ' ' });
    }
}

This will not compile, resulting in the following error:

‘ConsoleTestBed.Person.FirstName.get’ must declare a body because it is not marked abstract, extern, or partial

OK, so no joy there, I have to fill out the Getter. But notice in the Setter block there is no error! So I fill out the Getter and it looks like this:

// This compiles
public string FirstName
{
    get { return FirstName; }
    set
    {
        FirstName = value.TrimEnd(new char[] { ' ' });
    }
}

This compiles just fine. What I’m hoping at this point is that the Compiler will recognize what I am doing (given its context) and still create the variable for me. However, when I run it, I get a StackOverflowException. What you have probably figured out, and what I was afraid of, is that by referencing the Property name within the Property, I have created a recursion problem. So, unfortunately, I was originally correct: in order to make these changes work, I have to create a variable to support the Property:

// This compile AND works
private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value.TrimEnd(new char[] { ' ' });
    }
}

So if your program throws a StackOverflowException on a Property, be sure that you haven’t created a Recursion issue. Maybe someday the C# compiler guys can find a way to make this work based on the Context, or maybe a Property Attribute.

About these ads
Categories: .NET 3.5, C# 3.0
  1. Francis-Oliver
    November 24, 2010 at 8:21 pm

    Wow, great article.
    Shows really well everything we need to learn about properties.
    Thank you very much.

    //Sorry for my bad english;

  2. bhikshapathi
    February 22, 2012 at 3:45 pm

    great, it resolved my problem, thanks

  1. No trackbacks yet.
Comments are closed.
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: