c#: Inherited/interface static member? - c#

Is there a way to require that a class have a particular abstract member? Something like this:
public interface IMaxLength
{
public static uint MaxLength { get; }
}
Or perhaps this:
public abstract class ComplexString
{
public abstract static uint MaxLength { get; }
}
I'd like a way enforce that a type (either through inheritance or an interface?) have a static member. Can this be done?

You could create a custom attribute that allows enforcing the requirement as a runtime guarantee. This is not a fully complete code sample (you need to call VerifyStaticInterfaces in your application startup, and you need to fill in the marked TODO) but it does show the essentials.
I'm assuming you're asking this so you can guarantee successful reflection-based calls to named methods.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
internal sealed class StaticInterfaceAttribute : Attribute
{
private readonly Type interfaceType;
// This is a positional argument
public StaticInterfaceAttribute(Type interfaceType)
{
this.interfaceType = interfaceType;
}
public Type InterfaceType
{
get
{
return this.interfaceType;
}
}
public static void VerifyStaticInterfaces()
{
Assembly assembly = typeof(StaticInterfaceAttribute).Assembly;
Type[] types = assembly.GetTypes();
foreach (Type t in types)
{
foreach (StaticInterfaceAttribute staticInterface in t.GetCustomAttributes(typeof(StaticInterfaceAttribute), false))
{
VerifyImplementation(t, staticInterface);
}
}
}
private static void VerifyInterface(Type type, Type interfaceType)
{
// TODO: throw TypeLoadException? if `type` does not implement the members of `interfaceType` as public static members.
}
}
internal interface IMaxLength
{
uint MaxLength
{
get;
}
}
[StaticInterface(typeof(IMaxLength))]
internal class ComplexString
{
public static uint MaxLength
{
get
{
return 0;
}
}
}

This is impossible. Because abstract and virtual method calls are stored in an object though its virtual function pointer table, there is no way that you can enforce any interface requirement on its non-instance members. Calling a static member has no object bound to it, therefore there is no virtual pointer table available.
This isn't a limitation, its just how it is. There is no reason why this would ever be necessary or useful. If you want to enforce an interface, you must do it though instance members.

Not possible. May be you can try something like this:
public class Base
{
public struct MyStruct
{
public static int x = 100;
public static int XX()
{
return 200;
}
}
}
public class Derived : Base
{
public void test()
{
int x = Derived.MyStruct.x;
int XX = Derived.MyStruct.XX();
}
}
References:
Static C#

Suppose class Base includes a static method StaticMethod and an instance method InstanceMethod, both of which return Int32. Class Derived shadows both of those methods with similarly-named methods which return String.
If one casts an instance of derived to a Base and calls InstanceMethod, the call will use Base.InstanceMethod, whose return type is Int32. If one accepts an instance of generic type T, where T inherits Base, and calls InstanceMethod on that, it will likewise call Base.InstanceMethod--again Int32. But what should be the meaning and return type of T.StaticMethod? If one wants Base.StaticMethod, one should specify that. What else could T.StaticMethod usefully mean?

Related

use a generic type as parameter in C#

is there a method to tell a method which type a generic has? what i want to do is to tell the method it can be only an object of type A or B but nothing else, so i can work within like
if (myObject.GetType() == typeof(myTypeA)){doAstuff();}
if (myObjectGetType() == typeof(myTypeB)) {doBstuff();}
method<T>(T myObject){ T = myTypeA, T = myTypeB, T = nothing else}
thanks for any help
You could check for the type inside the method, then cast it to the appropriate type and do the appropriate "stuff":
public void method<T>(T myObject)
{
if (myObject is myTypeA)
{
myTypeA objA = myObject as myTypeA;
objA.DoA_Stuff();
}
else if (myObject is myTypeB)
{
myTypeB objB = myObject as myTypeB;
objB.DoB_Stuff();
}
else
{
return ;
}
}
But that would be a waste of generics. If they share some methods you could also make a base class, and let typeA and typeB inherit from it. Then your method could take a base class object as parameter:
public void method(BaseClass myObject)
and there would be only one if - case and one casting. Only the one with more methods then the base class.
EDIT:
Imagine you would have such a structure:
public class BaseType
{
public int SharedProp { get; set; } // shared property
public virtual int DoSharedStuff() // shared method
{
return SharedProp;
}
}
public class myTypeA : BaseType
{
public int A_Prop { get; set; }
// overwritten shared meth adjusted to the needs of type A
public override int DoSharedStuff()
{
return base.SharedProp + this.A_Prop;
}
}
public class myTypeB : BaseType
{
public int B_Prop { get; set; }
// overwritten shared meth adjusted to the needs of type B
public override int DoSharedStuff()
{
return base.SharedProp + this.B_Prop;
}
// individual method of Type B
public int DoB_Stuff()
{
return this.B_Prop;
}
}
Then you method would take only one of the children of the base class and execute according to the needs:
public void method(BaseType myObject)
{
// shared case: here type A will perform type A action
// and type B will perform type B action
myObject.DoSharedStuff();
// case B where you need really the extra stuff!
if (myObject is myTypeB)
{
myTypeB objB = myObject as myTypeB;
objB.DoB_Stuff();
}
}
This approach or phenomenon is called Polymorphism
You can restrict the allowed types for a gernic with the where command:
public void Test<T>(T param) where T : TypeA {
...
}
https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
But this are only simple constraints so it does not solve the problem for two classes but for this case you can use method overloading:
public void Test(TypeA param) {
...
}
public void Test(TypeB param) {
...
}
If you have only two classes I think that is the best solution because generics would have no benefits.

C# How to make a factory method return of the subclass type

[MAJOR EDITS, my first post was somewhat misleading. My appologies]
Given a class such as:
public class DatabaseResult{
public bool Successful;
public string ErrorMessage;
//Database operation failed
public static DatabaseResult Failed(string message) {
return new DatabaseResult{
Successful = true,
ErrorMessage = message
};
}
}
How can I implement subclasses such that I can add additional properties to represent data relevant to the particular operation (such as MatchedResult in the case of a SELECT type query) without the need to implement that static failure function? If I try to use plain inheritance, the return type will be of the parent class. Eg:
DoThingDatabaseResult : DatabaseResult {
public IEnumerable<object> SomeResultSet;
public static Successful(IEnumerable<object> theResults){
return new DoThingDatabaseResult {
Successful = true,
ErrorMessage = "",
SomeResultSet = theResults
};
}
//public static DatabaseResult Failed exists, but it's the parent type!
}
The goal is to avoid needing to copy the Failed static function for every subclass implementation.
Make it recursively generic:
public class BankAccount<T> where T : BankAccount<T>, new()
{
public T SomeFactoryMethod() { return new T(); }
}
public class SavingsAccount: BankAccount<SavingsAccount>{}
You'll note that I made the factory method non-static, because static methods aren't inherited.
You can't do this exactly as you have defined the question. The best way to tackle this is really to pull your factory out of the class completely:
public class BankAccount
{
}
public class SavingsAccount : BankAccount
{
}
public static class BankAccountFactory
{
public static T Create<T>() where T : BankAccount, new()
{
return new T();
}
}
Now the Factory has no dependency on the actual type. You can pass any derived class of BankAccount and get it back without doing any extra work or worrying about inheriting your factory method.
If I may, I'd like to expand upon StriplingWarrior. In fact, you can use static for the factory. This following code shows that a and c are the expected object types. The limit is you cannot use the factory on the base class itself.
private void Testit()
{
var a = SavingsAccount.Factory();
var c = CheckingAccount.Factory();
//var b = BankAccount.Factory(); //can't do this
}
public class BankAccount<T> where T : BankAccount<T>, new()
{
public static T Factory()
{
return new T();
}
}
public class SavingsAccount : BankAccount<SavingsAccount>
{
}
public class CheckingAccount : BankAccount<CheckingAccount>
{
}
In order to use inheritance, you need an instance of an object and a member of that object. In this case, for the object we can't use BankAccount/SavingsAccount because then we would already have what we're trying to get. This means we need an actual factory object, which is what most people are talking about when they talk about a factory. So if we pull that out into a Factory and use inheritance...
public class BankAccountFactory { public virtual GetAccount() { return new BankAccount(); } }
public class SavingsAccountFactory : BankAccountFactory { public override GetAccount() { return new SavingsAccount(); } }
But now how do we get an instance of the proper type? We've just pushed our problem one layer deeper.
Instead, what you probably want to do, is use some sort of configuration to determine the type, or pass the type you want into a method.
public BankAccount GetAccount(AccountType type) { /* */ }
or
public BankAccount GetAccount() { /* Access config */ }
For a simple answer to your question: You don't need to use generics or anything like that, you just need your method to not be static...

C# Give access to specific unrelated class

Is there a way to modify the access of some attribute to a specific class? More specifically, I want to create a property that has a public get, but can only be set by a certain class.
Example:
public Class1
{
Class2.SomeInt = 5;
}
public static Class2
{
private static int someInt;
public static int SomeInt
{
get { return someInt; }
(give access to Class1 only somehow?) set { someInt = value; }
}
}
Update (more info):
I'm doing this in xna, I want the main type (Game1) to be the only thing that can modify a static helper class. It's for a group project in school, we're using SVN (not sure how that'd be relevant), I could just tell everyone in my group to avoid setting the values, but I was wondering if there was a better way.
This sounds like the friend access modifier, which C# doesn't have. The closest I've seen to this in C# is to have the "unrelated" class be an interface and have a private implementation within a class. Something like this:
public interface IWidget
{
void DoSomethingPublic();
}
public class SomeObject
{
private ObjectWidget _myWidget = new ObjectWidget();
public IWidget MyWidget
{
get { return _myWidget; }
}
private class ObjectWidget
{
public void DoSomethingPublic()
{
// implement the interface
}
public void DoSomethingPrivate()
{
// this method can only be called from within SomeObject
}
}
}
Code external to SomeObject can interact with MyWidget and sees anything that's on the IWidget interface, but code internal to SomeObject can also non-interface public members on MyWidget.
It seems to be impossible in C#. You can only use public, protected, protected internal, internal and private access modifiers.
But you can, for instance, make an assembly that contains only these two classes and set the internal modifier for the SomeInt setter or nest one class into another.
If you want to just hide a setter from the IntelliSense, you can define this setter in some interface and implement it explicitly:
public interface IHidden<T>
{
T HiddenPropery { set; }
}
public class SomeClass : IHidden<int>
{
private int someInt;
public int HiddenPropery
{
get { return someInt; }
}
int IHidden<int>.HiddenPropery
{
set { someInt = value; }
}
}
Usage:
// This works:
((IHidden<int>)new SomeClass()).HiddenPropery = 1;
// This doesn't:
new SomeClass().HiddenPropery = 1;

Type-safe setting of objects with a dictionary that has a `Type` key

I have a generic dictionary of objects where the key is of type Type:
public class DynamicObject : IDictionary<Type, object>
The idea is that this object is shared in a plugin-based architecture and so a type (which could reside in a plugin .dll) is used as a key in order to prevent clashes between plugins. This type is also used to store metadata about the field (such as a description of that field or the actual type of that field).
Currently plugins need to set the value of fields on this object using code similar to this:
DynamicObject someObject;
string someValue;
someObject[typeof(UsernameField)] = someValue;
The only problem with this is that this isn't type safe - even though the type UsernameField is aware of the exact type of the value it is expecting (e.g. int or in this case string), the value supplied here is just typed as an object. I'd like to use generics to make setting / getting of properties type safe but I'm not sure how. So far the best I've come up with is this:
// Field is a base class for all types used as keys on DynamicObject
[Description("Username of the user")]
public class UsernameField : Field
{
public static void Set(DynamicObject obj, string value)
{
obj[typeof(UsernameField)] = someValue;
}
}
// To set fields
UsernameField.Set(obj, someValue);
This is type safe, however it means that each of my field types (e.g. UsernameField) has a nearly identical static Set method.
How can I have type-safe access to values in this way without having lots of nearly identical methods on each of my field types?
As an aside, is using Type as a key like this a good idea or are there hidden pitfalls that I'm not yet aware of?
Define an interface that all your plugins must implement:
public interface IPlugin {
string Name { get; }
string Author { get; }
string Description { get; }
void Init();
}
And then use a Dictionary<Type, IPlugIn>.
Typically the interface is declared in a separate dll (like "MyCompany.MyProject.PlugIns.Contracts.dll").
EDIT: Ok, I think that I know what you mean now.
The trick is to have a generic class between Field and UsernameField with a generic Set method. The fact that Field is not generic, makes all the field types assignable to it. This would not be the case, if it was declared as Field<T>.
public abstract class Field
{
}
public abstract class GenericField<T> : Field
{
public void Set(DynamicObject obj, T value)
{
obj[this.GetType()] = value;
}
}
public class UsernameField : GenericField<string>
{
#region Singleton Pattern
public static readonly UsernameField Instance = new UsernameField();
private UsernameField() { }
#endregion
}
Because we need to call GetType in the Set method, we cannot declare it as static. Therefore, I used the singleton pattern.
Now, we can set the field in a type safe way:
UsernameField.Instance.Set(obj, "Joe");
ADDITION 1:
Since now the fields are singletons, you could use the fields as key of the dictionary instead of their type.
public class DynamicObject : IDictionary<Field, object> { }
And Set would become:
public void Set(DynamicObject obj, T value)
{
obj[this] = value;
}
ADDITION 2:
You could also define DynamicObject like this:
public class DynamicObject : Dictionary<Field, object>
{
public void Set<T>(GenericField<T> field, T value)
{
this[field] = value;
}
}
Now you can set values like this:
obj.Set(UsernameField.Instance, "Sue");
This is type safe and seems more natural. The Set method in GenericField is obsolete now.
Fields shouldn't have to know about a DynamicObject to get and set the value. You could make DyanmicObject handle the getting and setting of values, but I think a better approach is to treat the DynamicObject as a collection of Field instances, and each field has its own value. Something like this:
interface IField
{
object Value { get; set; }
}
interface IField<T> : IField
{
new T Value { get; set; }
}
abstract class BaseField<T> : IField<T>
{
T _value;
public T Value
{
get { return _value; }
set
{
// could add stuff like OnValueChanging, IsValueValid, etc...
this._value = value;
}
}
object IField.Value
{
get { return Value; }
set { Value = (T)value; }
}
}
class DynamicObject : List<IField>
{
public TField GetField<TField>() where TField : IField
{
return this.OfType<TField>().Single();
}
}
And the usage would then be:
class UsernameField : BaseField<string> { }
[TestMethod]
public void test()
{
var parent = new DynamicObject();
var field = new UsernameField() { Value = "the username" };
parent.Add(field);
Assert.AreEqual("the username", parent.GetField<UsernameField>().Value);
}
I may just be missing the point of the question but if the goal is to reduce the amount of code duplication required to achieve type safety, then why not define accessor helpers based on the type of field rather than the field itself:
public abstract class StringField<T> : Field
{
public static void Set(DynamicObject obj, string value)
{
obj[typeof(T)] = someValue;
}
}
public class UsernameField : StringField<UsernameField> { }
// To set fields
UsernameField.Set(obj, someValue);
Edit:
Or you could use a slight variation of Oliver's solution without the Singleton:
public abstract class GenericField<T, U> : Field
{
public static void Set(DynamicObject obj, T value)
{
obj[typeof(U)] = value;
}
}
public class UsernameField : GenericField<string, UsernameField> { }

Attributes: Access Designation

While I was refering to a book , I got the following statements:
When a data type or method is defined as public , Other Objects can directly access it. When a data type or method is defined as private , only the specific object can access it.
Now this is really confusing. Public and Private are Access Specifiers which only define the scope of a attribute or method.
Why object is mixed with access specifiers? Does object has to do any thing with public , private or protected apart from the fact that if some thing is defined as public then objects too will be able to access irespective of the scope
This is not a scope question but an access limitation modifier. If you declare a function as private that means only that class can call that function.
Public:
Any one can call these functions
Private:
Only that class and the refection engine
Protected:
Only that class and its derived member
Internal:
Public to all the classes in that assembly
A small ex
public class A
{
public int x;
protected int y;
private int z;
}
public class B : A
{
public int CallPro()
{
return y;
}
public int CallPriv()
{
return z; //error
}
}
static void Main()
{
A oa;
oa.x; //Fine
oa.y; //Error
oa.z; //Error
}
Public and Private are Access Specifiers which only define the scope
of a attribute or method.
And that defines the behaviour of the object. Hence the access specifiers are important for the object. Imagine if you have a facade kind of object, you don't want to expose all the details of the operation, rather you want a simple public interface (eg, Save() method) to be exposed for the consumers. That's why you have to consider the specifiers for objects.
public class CustomerFacade()
{
public bool Save(Customer c)
{
VerifyCustomer(c);
// lots of other steps which the caller does not need to know
SaveorUpdateCustomer(c);
}
private void VerifyCustomer(Customer c)
{
}
private void SaveorUpdateCustomer(Customer c)
{
}
}
public class CustomerController()
{
public bool Save(Customer c)
{
return new CustomerFacade().Save(c);
}
}

Categories

Resources