2

In PHP we can remove one property and its value from the object simply with this code:

$foo->bar = "Something";
unset($foo->bar);

I want to do this in C#.

Imagine that the object is:

var a = new {foo = bar, one = "one"}

How I can remove foo from the object?

  • For anyone landing here a year and a half later: In this specific case, dynamic types are a good fit. Take a look at this question: https://stackoverflow.com/q/14491577/166848 – Zano Sep 10 '20 at 12:13

1 Answers1

5

Types are defined at compile-time, so there's no removing of properties, not in c#. An anonymous type is a type just like classes that you create; it's just that the name is hidden from you.

The closest you can get to your answer is to define a new type that omits the property you wish to remove:

var b = new { one = a.one };
John Wu
  • 50,556
  • 8
  • 44
  • 80