I am inheriting from a class that has this property :
public bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
I am trying to override this in the derived class, but it doesn't recognise isAuthorized. Can someone help me with my syntax?
public override bool isAuthorized()
{
}
This is the error I get :
cannot override because 'CDBase.isAuthorized' is not a function
EDIT : So if I want the override to always set isAuthorized to true, I would use this syntax?
private bool _Authorized = false;
public override bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = true; }
}
its a property, you used as method isAuthorized()
() - used for methods
you have to do in your derived class
public override bool isAuthorized
{
}
To set your value always to true you can simply write this code:
public override bool isAuthorized
{
get { return true; }
}
Same as when you want your method to be overridable, the property also has to be declared virtual in the base class:
public virtual bool isAuthorized ...
Also you cannot override a propeprty with a method. You can only override the getters and setters in the derived class:
public override bool isAuthorized
{
get { return base.isAuthorized; }
set { base.isAuthorized = value; }
}
The original class should have a virtual, but I suspect you might also have an issue with the fact that you are trying to override a base class property with a derived class method.
If your derived class method looked like this:
public override bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
Then you would need this in your base class:
public virtual bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
Can you maybe desrive more what you are trying to achieve?
public virtual bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
public override bool isAuthorized
{
...
}
In base class mark the property as virtual which you want to be overridden and in derive class use override keyword for the property that needs to be overriden.
this
class A
{
public virtual string prop { get; set; }
}
class B : A
{
public override string prop
{
get
{
return "overridden";
}
set
{
base.prop = value;
}
}
}
Hi I think you must declare this as Virtual in able to override
Like:
public virtual bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
Regars,
In base class you can mark it as virtual, and you can override.
Actually, use reflector we can see the properties are methods, too!
About your error and syntax :
Simply dont use the '()' . You are using property as method.
About how to do it :
There are two ways to implement it in base class. 'new' and 'override'. But their implementations varies regarding to base class.
http://msdn2.microsoft.com/en-us/library/435f1dw2.aspx
The new modifier instructs the compiler to use your implementation instead of the base class implementation. Any code that is not referencing your class but the base class will use the base class implementation.
public bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
public new bool isAuthorized
{ //someth }
http://msdn2.microsoft.com/en-us/library/ebca9ah3.aspx
The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.
public virtual bool isAuthorized
{
get { return _Authorized; }
set { _Authorized = value; }
}
public override bool isAuthorized
{ //someth }
Related
The main purpose is to show intellisense when setting the property. It would be great if I could do it via an attribute like the image below.
The property should remain a string(not enum or struct) so that Mongo's BsonSerializer can serialize it properly. Here is an example of what it might look like:
To help other developers on the team know possible (but not exlusive) values they can use for the Type field Code Completion should display values that can be used as shown below:
(Edited) I was able to solve this by creating my own type
public class SkinType:StringType<SkinType>
{
public SkinType(string value)
{
Value = value;
}
public SkinType()
{
}
public static implicit operator string(SkinType d)
{
return d.Value;
}
public static implicit operator SkinType(string d)
{
return new SkinType(d);
}
public const string StringValue = nameof(StringValue);
public const string Color = nameof(Color);
}
Now I get intellisense for my Type property and Mongo knows how to serialize it.
Here is how I use it:
public class Skin : ServiceMongoIdentity
{
//removed some properties for brevity.
[BsonIgnoreIfDefault]
[BsonDefaultValue(SkinType.StringValue)]
public SkinType Type { get; set; } = SkinType.StringValue;
}
Here is how the StringType base class is defined. I had to make Value public because Generics cannot have constructors with parameters
public abstract class StringType<T> where T :StringType<T>,new()
{
[ReadOnly(true)]
public string Value;
public T FromString(string d)
{
return new T
{
Value = d
};
}
public override bool Equals(object obj)
{
return obj?.ToString() == Value;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return Value;
}
}
I have two classes Inherited from ICart interface
When I create an object from this classes I want only Guest class show me IsInfoExist property. How am I gonna do that?
ICart cart = new Guest();
bool c = cart.IsInfoExist //it's ok
ICart cart = new Member();
cart.IsInfoExist not ok.
Actually I dont want never appear on intellinsense but Interface force me to show Member IsInfoExist property
class Guest:ICart
{
public bool IsInfoExist
{
get { return Session["guest_info"] != null; }
}
public void GetCart()
{
}
}
class Member:ICart
{
//Hide this on intellinsense always!
public bool IsInfoExist
{
get { return false; }
}
public void GetCart()
{
}
}
public interface ICart
{
void GetCart();
bool IsInfoExist { get; }
}
By explicitly implementing the property:
bool ICart.IsInfoExist
{
get { return Session["guest_info"] != null; }
}
If you have a Member or a Guest instance, it won't have an IsInfoExist unless you explicitly cast it to an ICart.
Member myMember = new Member();
bool test = myMember.IsInfoExist; // won't compile.
bool test1 = ((ICart) myMember).IsInfoExist; // will compile.
If IsInfoExists only must be in Guest class, remove it from the interface and leave it as is in the Guest class.
A class implementing a interface must implement all methods in it, but it can have other methods that does not belong to the interface and are specific to that class. Is a nonsense having to implement IsInfoExists in the Member class only to hide it afterwards. So, it would be something like:
public interface ICart
{
void GetCart();
}
class Guest:ICart
{
public bool IsInfoExist
{
get { return Session["guest_info"] != null; }
}
public void GetCart()
{
}
}
class Member:ICart
{
public void GetCart()
{
}
}
Edit
It seems the problem with this approach for you is that you are always using variables of type ICart and this way you can't access that method. But you can, you just have to cast it to the correct type,something like this:
ICart cart = new Guest();
ICart cart2 = new Member();
if (cart is Guest)
{
bool info=((Guest)cart).IsInfoExist;
}
if (cart is Member)
{
bool info=((Member)cart).IsInfoExist; //this won't compile as IsInfoExist is not in the Member class
}
Use two interfaces to accomplish that. Like ICart and ICartInfo for example. In this case you have a clear seperation and it would make your code cleaner and better to read.
I guess there is no way.
Closest solution is
[Obsolete("Only Guest Member", true)]
public bool IsInfoExist
{
get { return false; }
}
I'm gonna use this. Thanks
I have a base class called Message like this:
public abstract class Message
{
protected int m_id;
protected bool m_localized;
protected string m_metaData;
public int GetID() { return m_id; }
public bool GetLocalized() { return m_localized; }
public string GetMetadata() { return m_metaData; }
}
Then, i have two more classes that inherit from Message for example:
public class ClassicMessage : Message
{
private string m_title;
private string m_content;
public void SetTitle(string title) { m_title = title; }
public void SetContent(string content) { m_content = content; }
public string GetTitle() { return m_title; }
public string GetContent() { return m_content; }
}
public class MessageWithCustomContent : Message
{
private List<CustomContent> m_content;
public MessageWithCustomContent()
{
m_content = new List<CustomContent>();
}
public List<CustomContent> GetContent()
{
return m_content;
}
public CustomContent GetContentEntry(int id)
{
return m_content.find(x => x.ID.Equals(id));
}
}
public class CustomContent
{
private int m_id;
public int ID { get; set { m_id = value; } }
private string m_body;
public string Body { get { return m_body; } set { m_body = value; }
private Image m_image;
public Image Image { get { return m_image; } set { m_image = value; } }
}
In a case like this, how can i unify the app interface if the derived classes has similar methods but these methods have different return types? (even when the methods try to do the same)
I know that with the example i'm breaking the Liskov Substitution Principle and the Open/Closed principle, what's the best approach to get around with that?
Thanks for your help!
Edit:
For more clarity, what i'm trying to achieve is to create a common interface to manage all the possible messages as the base "Message", because i want to avoid using typeof in the consumer class.
for example:
if(message is MessageWithCustomContent)
{
// do something with the contents.
}
else if(message is MessageWithCustomContent)
{
// do another thing with the contents.
}
etc...
You could change Message to be generic, and the T would specify the Content return type. See example below.
Edit
You could use a "IMessage" and a "Message: IMessage" as base.
You would then be able to create a IMessage list like so
var messages = new List<IMessage>
{
new ClassicMessage(),
new MessageWithCustomContent()
};
foreach (var message in messages)
{
message.GetContent();
}
Below is how the implementation of IMessagecould be done.
public interface IMessage
{
int GetID();
bool GetLocalized();
string GetMetadata();
object GetContent();
}
public abstract class Message<T> : IMessage
{
protected int m_id;
protected bool m_localized;
protected string m_metaData;
public int GetID() { return m_id; }
public bool GetLocalized() { return m_localized; }
public string GetMetadata() { return m_metaData; }
object IMessage.GetContent()
{
return GetContent();
}
public abstract T GetContent();
}
public class ClassicMessage : Message<string>
{
private string m_title;
private string m_content;
public void SetTitle(string title) { m_title = title; }
public void SetContent(string content) { m_content = content; }
public string GetTitle() { return m_title; }
public override string GetContent()
{
return m_content;
}
}
public class MessageWithCustomContent : Message<List<CustomContent>>
{
private List<CustomContent> m_content;
public MessageWithCustomContent()
{
m_content = new List<CustomContent>();
}
public CustomContent GetCustomContent(int id)
{
return null;
}
public override List<CustomContent> GetContent()
{
return m_content;
}
}
public class CustomContent
{
private int m_id;
public int ID { get; set; }
private string m_body;
public string Body
{
get { return m_body; }
set { m_body = value; }
}
}
I will explain how you break LSP below but before I do that, you are not really doing any inheriting. Yes you are declaring your classes to be inheriting but you are not really inheriting anything. So before learning LSP, perhaps you need to get a grip on inheritance firstly.
How do I know if I am breaking LSP?
Lest say your Message class was like this, notice the virtual and abstract methods:
public abstract class Message
{
protected int m_id;
protected bool m_localized;
protected string m_metaData;
public virtual int GetID() { return m_id; }
public virtual bool GetLocalized() { return m_localized; }
public abstract string GetMetadata();
}
Create a list like this:
var messages = new List<Message>();
Then add concrete types to that list of all the inheriting types. Then do this:
foreach(var thisMessage in messages)
{
var id = thisMessage.GetID();
var loc = GetLocalized();
var meta = GetMetadata();
}
If you get no exception thrown because one of the inheriting classes decided it does not need one of those methods, then you have not broken LSP. The idea is that if something is inheriting Message, then it should inherit everything. Otherwise, we cannot safely and with confidence substitute the inherited one for the parent one.
The reason this principle is important is because there may be existing code which is using Message, as shown in the foreach above, where it is treating all the types polymorphically and a developer decides to inherit it like this:
public abstract class BadMessage
{
public override int GetID()
{
throw new InvalidOperationException
("This method is not needed for BadMessage and should not be called");
}
public override bool GetLocalized() { ... }
public override string GetMetadata() { ... }
}
You see this will break existing code. And the worst part is, the compiler will not even be able to catch it, until it surfaces like an ugly bug in production.
Well, you're missing the interface methods in de base class. Abstract functions, that get implemented in the derivative classes. If you get a Message, not knowing what kind it is, how would you request its contents?
You could add derivative-specific methods to your base, but you'd have to implement an not_implemented exception in a virtual implementation in the base class to compensate for all derivatives not implementing it, and add exception handling. But then you should ask yourself: " is this class really a derivative? What do I want to achieve."
Imagine you have a class hierarchy as:
class Base
{
public virtual string GetName()
{
return "BaseName";
}
}
class Derived1 : Base
{
public override string GetName()
{
return "Derived1";
}
}
class Derived2 : Base
{
public override string GetName()
{
return "Derived2";
}
}
In most appropriate way, how can I write the code in a way that all "GetName" methods adds "XX" string to return value in derived class?
For example:
Derived1.GetName returns "Derived1XX"
Derived2.GetName returns "Derived2XX"
Changing the code of GetName method implementation is not good idea, because there may exist several derived types of Base.
Leave GetName non-virtual, and put the "append XX" logic in that function. Extract the name (without "XX") to a protected virtual function, and override that in the child classes.
class Base
{
public string GetName()
{
return GetNameInternal() + "XX";
}
protected virtual string GetNameInternal()
{
return "BaseName";
}
}
class Derived1 : Base
{
protected override string GetNameInternal()
{
return "Derived1";
}
}
class Derived2 : Base
{
protected override string GetNameInternal()
{
return "Derived2";
}
}
This is a good use case for the decorator pattern. Create a decorator that has a reference to a Base:
class BaseDecorator : Base
{
Base _baseType;
public BaseDecorator(Base baseType)
{
_baseType = baseType;
{
public override string GetName()
{
return _baseType.GetName() + "XX";
}
}
Construct a BaseDecorator with your chosen class (Base or Derived), and call GetName on that.
If you don't want to (or can't) modify original classes, you can use extension method:
static class Exts {
public static string GetNameXX (this Base #this) {
return #this.GetName() + "XX";
}
}
You'll be able to access new method as usual:
new Derived1().GetNameXX();
You could split the construction of the name into various overridable parts and then override each part in each of the different subclasses.
Below is one such example.
public class Base {
public string GetName() {
return GetPrefix() + GetSuffix();
}
protected virtual string GetPrefix() {
return "Base";
}
protected virtual string GetSuffix() {
return "";
}
}
public class DerivedConstantSuffix : Base {
protected override string GetSuffix() {
return "XX";
}
}
public class Derived1 : DerivedConstantSuffix {
protected override string GetPrefix() {
return "Derived1";
}
}
public class Derived2 : DerivedConstantSuffix {
protected override string GetPrefix() {
return "Derived2";
}
}
An override can call it's base function... you could then modify the base class to append the characters you want there.
I got an abstract base class
public class Base
{
public abstract String Info { get; }
}
and some children.
public class A : Base
{
public override String Info { get { return "A does ..."; } }
}
public class B : Base
{
public override String Info { get { return "B does ..."; } }
}
This is mere a constant but I want to make sure using Base that all classes implement it.
Now I sometimes do not have an object instance but want to access A.Info - this is not possible due it is a instance property.
Is there another way than implementing the same property on instance AND on static level? That would be feel like a duplicate violating DRY programming style.
NEW EDIT: I now see this two solutions:
public class Base
{
public abstract String ClassInfo { get; }
}
public class A : Base
{
public override String ClassInfo { get { return Info; } }
public static String Info { get { return "A does ..."; } }
}
public class B : Base
{
public override String ClassInfo { get { return Info; } }
public static String Info { get { return "In B we do ..."; } }
}
With this I can do with any object of type Base something like object.ClassInfo but also use the value in my factory hardcoded like if(A.Info) return new A(). But I have to implement two properties for the same information in every class.
On the other hand:
public class Base
{
public abstract String ClassInfo { get; }
public static String GetClassInfo<T>() where T : BaseControl, new()
{
T obj = new T();
return obj.ClassInfo;
}
}
public class A : Base
{
public override String ClassInfo { get { return "text A"; } }
}
public class B : Base
{
public override String ClassInfo { get { return "text B"; } }
}
Due to the abstract Base it is made sure that ClassInfo is always implemented. Calls with obj.ClassInfo and Base.GetClassInfo<A>() are okay. But with this every child of Base must have a default constructor without arguments and we loose performance with the unneccessary created instance.
Is there any other idea? Which one would you prefer and why?
If you need specific return results of your static properties, you're better of either
a) Instance properties
2) Attributes
In the example you've already given, you've got an instance of Base, which means you can just make the instance property virtual:
public class Base
{
public virtual string Info { get { return "From Base"; } }
}
public class A : Base
{
public override string Info { get { return "From A"; } }
}
If you wanted to go the attribute route, you define it as such:
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class InfoAttribute : Attribute
{
public InfoAttribute(string info) { this.Info = info; }
public string Info { get; private set; }
}
[InfoAttribute(Info = "From Base")]
public class Base
{
public string GetInfo()
{
var attr = GetType()
.GetCustomAttributes(typeof(InfoAttribute), true)
.FirstOrDefault();
return (attr == null) ? null : attr.Info;
}
}
[InfoAttribute(Info = "From A")]
public class A : Base { }
If you wanted to call it as a static function call, you could make this change:
public static string GetInfo(Base instance)
{
var attr = instance.GetType()
.GetCustomAttributes(typeof(InfoAttribute), true)
.FirstOrDefault();
return (attr == null) ? null : attr.Info;
}
And then call it as: Base.GetInfo(instance);. All in all, not very elegant!
This is not possible.
static members cannot be virtual or abstract.
You should make an abstract instance property.
Statics can't be overridden. If you truly want to do something like that, you'd want an instance property that is virtual in the base that gets overridden in the subclasses.
Does it compiled? I don't think so. Static cannot be marked as override, virtual or abstract.