R
Rekkonsider
Guest
Note: this question was migrated from a relevant question on Developer Community.
While trying to answer a question on StackOverflow (will provide link whenever Microsoft allows me to), I encountered that in the following code, a NullReferenceException is being thrown in the first line of GetCensored(). Through trial and error, removing the sealed keyword from the GetCensored() method will not throw the exception. In the posted answer this has been mentioned. This is the code that has been used:
public static class Program
{
public static void Main(string[] args)
{
var user = new User();
var censored = ((ICensoreable<User>)user).GetCensored();
}
}
public interface ICensoreable<T>
where T : new()
{
sealed ICensoreable<T> GetCensored()
{
var result = Clone();
result.CensorInformation();
return result;
}
ICensoreable<T> Clone();
void CensorInformation();
}
public class User : ICensoreable<User>
{
public User() { }
public User(User other)
{
name = other.name;
password = other.password;
}
public string name;
public string password;
public void CensorInformation()
{
password = null;
}
public User Clone() => new User(this);
ICensoreable<User> ICensoreable<User>.Clone() => Clone();
}
Continue reading...
While trying to answer a question on StackOverflow (will provide link whenever Microsoft allows me to), I encountered that in the following code, a NullReferenceException is being thrown in the first line of GetCensored(). Through trial and error, removing the sealed keyword from the GetCensored() method will not throw the exception. In the posted answer this has been mentioned. This is the code that has been used:
public static class Program
{
public static void Main(string[] args)
{
var user = new User();
var censored = ((ICensoreable<User>)user).GetCensored();
}
}
public interface ICensoreable<T>
where T : new()
{
sealed ICensoreable<T> GetCensored()
{
var result = Clone();
result.CensorInformation();
return result;
}
ICensoreable<T> Clone();
void CensorInformation();
}
public class User : ICensoreable<User>
{
public User() { }
public User(User other)
{
name = other.name;
password = other.password;
}
public string name;
public string password;
public void CensorInformation()
{
password = null;
}
public User Clone() => new User(this);
ICensoreable<User> ICensoreable<User>.Clone() => Clone();
}
Continue reading...