New Keyword Interview Question

22 Sep 21 (1 min read)
// object
var str = new StringBuilder();
str.Append("new operator");

// array
var newTypes = new int[3];
newTypes[0] = 1;
newTypes[1] = 2;
newTypes[2] = 3;

// anonymous
var a = new { Text = "anonymous object" };
Console.WriteLine($"{a.Text}");
// constraint
public class Factory<T> where T : new()
{
  public T Create()
  {
    var o = new T();
    // initialize 'o' with common params
    return o;
  }
}
// modifier
public class BaseClass
{
    public string Name { get; } = "Base";
}

public class DerivedClass : BaseClass
{
    public new string Name { get; } = "Derived";
    // just change the name b/c they really are 2 different members
    public string Name2 { get; } = "Derived";
}
< back