Ahmadreza's Notes

On .NET Framework and Software Architecture

Value type property and C# compilation error

leave a comment »

Two days ago a question was asked in StackOverflow.com and I found this question so good to prepare a post. I want to explain this question:

Petr asked: I do not understand why there is Control.padding.all which is int and according to hint there is set as well as get but I cannot set it (Control.Padding.All=5)? I would be grateful for explanation.

For example when you want to set

textBox1.Padding.All = 5;

You will get this compiling error: Cannot modify the return value of ‘System.Windows.Forms.TextBoxBase.Padding’ because it is not a variable

Following example is an implementation of this error:

public class ARAControl 
{ 
    public ARAPadding Padding { get; set; } 
}
public struct ARAPadding 
{ 
    public int All { get; set; } 
}

If you use this you’ll get mentioned error:

	ARAControl control = new ARAControl();
	control.Padding.All = 10;

And why this compiling error happens. It hapens because structure is a value type. By setting this property you first call get Method. “Property Get” will return a copy of ARAPadding, so it is a value type and C# will detect out mistake and prevent compiling.

Advertisement

Written by Ahmadreza Atighechi

November 28, 2009 at 9:48 pm

Posted in Blog

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.