Consider the following code:
public class SystemManager<T> where T : ISettings
{
public SystemManager()
{
T implicit1 = default(T);
T implicit2 = default(T);
if (implicit1 != implicit2)
{
// This will not compile saying the compiler cannot compare
// using '!=' two objects of type 'T' and 'T'
}
ISettings explicit1 = null;
ISettings explicit2 = null;
if (explicit1 != explicit2)
{
// This will compile fine
}
}
}
In the above, the compiler knows that T is ISettings, so why does the comparison only work out of the scope of generics? Is this going to be one of those ".NET 4 is the answer" things?
Edit:
In answer to Manu's question, why use generics as opposed to ISettings directly.
Suppose the following:
void Main()
{
SystemManager<XmlSettings> manager = new SystemManager<XmlSettings>();
// I want to disallow the following
SystemManager<RegistrySettings> manager = new SystemManager<RegistrySettings>();
}
public interface ISettings
{
}
public class XmlSettings : ISettings, IDisposable
{
public void Dispose() { }
}
public class RegistrySettings : ISettings
{
}
This way I disallow any implementations of ISettings that do not implement IDisposable. I don't have control over ISettings and cannot make the other classes implement an ISettingsDisposable class, for example.
Disposable is one example, obviously, but you could put anything there - the idea being I may want to restrict tighter than just ISettings.
Edit 2:
In response to points about structs not being == able:
public struct StructSettings : ISettings
{
}
I could do the above and implement a generic, StructSettings
version of SystemManager:
Then, in SystemManager I can compare the two structs with no runtime error.
SystemManager<StructSettings> manager = new SystemManager<StructSettings>();
This works, and the == on the structs in the constructor of SystemManager does not throw any runtime errors.