-1

I wanted to add property using var keyword.

  public async Task<MyObject> ManageObjectAsync(string actionparam, int objectid)
  {
    // var bodyObj = { action = "enable"}; //it is working fine
    var bodyObj = new {};
    if (actionparam == "enable")
        //bodyObj.
  }

For inline assignment it is okay, but when I try to set value I can't find a way to do that

BlackCat
  • 1,932
  • 3
  • 19
  • 47
  • 4
    `dynamic`, and I'd really advice **against** going down this route. – gunr2171 Feb 23 '23 at 19:59
  • Not just `dynamic`, but a `dynamic ` variable with a reference to an `ExpandoObject` instance, or something else that can have arbitrary properties assigned at run time. `dynamic` with an anonymous type, for example, won't do that. But yes, better to avoid that and use named, purpose-specific types at this point. Far more maintainable. – madreflection Feb 23 '23 at 20:03
  • 1
    I believe that you're trying to set a value on an anonymous object here. Doing it the "native" way won't work because anonymous type properties are read only and they cannot be set, as explained here https://stackoverflow.com/questions/17441420/how-to-set-value-for-property-of-an-anonymous-object. However, you can work it around as said in the other comments and achieve your goal. – anthino12 Feb 23 '23 at 20:03

1 Answers1

0

In C#, the var keyword is used to declare a variable with implicit typing. When you use var, the compiler infers the type of the variable based on the type of the expression on the right-hand side of the assignment.

In your code, you have declared bodyObj as an anonymous object with an empty initializer. Anonymous objects are read-only, meaning you cannot modify their properties once they are created.

To add a property to your anonymous object, you can modify your code to use an object initializer like this:

public async Task<MyObject> ManageObjectAsync(string actionparam, int objectid)
{
  var bodyObj = new { action = "enable" };
  if (actionparam == "enable")
  {
    bodyObj = new { action = "enable", id = objectid };
  }
  // rest of your code
}

In the example above, we initialize bodyObj with an anonymous object that has a action property set to "enable". Then, inside the if block, we create a new anonymous object that has the action property set to "enable" and a new id property set to the value of objectid. We then assign this new object to bodyObj, effectively adding a new property to the anonymous object.

Note that this creates a new anonymous object each time you assign to bodyObj, so any previous properties that were set will be lost. If you need to add multiple properties, you can chain object initializers like this:

var bodyObj = new { action = "enable" };
if (actionparam == "enable")
{
  bodyObj = new { action = "enable", id = objectid, name = "my object" };
}

n this example, we're adding two new properties to the bodyObj object, id and name.

Zarik
  • 65
  • 6