Wednesday, September 15, 2010

PropertyInfo.SetValue()

Consider the following example.

We have a class named Foo:
class Foo
{
public int Bar{get;set;}
}


What is the result of the following code execution?

var property = typeof(Foo).GetProperty("Bar");
Foo foo = new Foo {Bar = 5};
property.SetValue(foo, null, null);
Console.WriteLine(foo.Bar);

It is a surprise, but the code will be executed without any exceptions and foo.Bar will actually has value equal to 0 (zero). There is no explanation in MSDN, but PropertyInfo.SetValue(..., null, ...) will set a default value to the referenced property, even if the property is value-typed.

2 comments:

  1. и вовсе не stupid. я, например, в уме не придумал правдоподобный ответ.
    ясно одно - должна быть ошибка по идее, но какая?? TypeCast не катит, и NullRef тоже не при делах...

    ReplyDelete
  2. Все немного страньше.

    ReplyDelete