Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the 'is' functionality

Tags:

c#

I have a class so contains a exception, as so.

public class ExceptionWrapper {     public string TypeName { get; set; }     public string Message { get; set; }     public string InnerException { get; set; }     public string StackTrace { get; set; }      public ExceptionWrapper() { }      public ExceptionWrapper(Exception ex)     {         TypeName = String.Format("{0}.{1}", ex.GetType().Namespace, ex.GetType().Name);         Message = ex.Message;         InnerException = ex.InnerException != null ? ex.InnerException.Message : null;         StackTrace = ex.StackTrace;     }      public bool Is(Type t)     {         var fullName = String.Format("{0}.{1}", t.Namespace, t.Name);         return fullName == TypeName;     } } 

I want to override the 'is' action, So instead of doing so

if (ex.Is(typeof(Validator.ValidatorException)) == true) 

I will do so

if (ex is Validator.ValidatorException) 

Is it possible? How?

like image 443
Yacov Avatar asked Dec 18 '13 08:12

Yacov


People also ask

Why function overriding is used?

Function overriding helps us achieve runtime polymorphism. It enables programmers to perform the specific implementation of a function already used in the base class.

What is function overriding with example?

Example 1: C++ Function Overriding So, when we call print() from the Derived object derived1 , the print() from Derived is executed by overriding the function in Base . As we can see, the function was overridden because we called the function from an object of the Derived class.

What is overriding in functional programming?

Overriding is an object-oriented programming feature that enables a child class to provide different implementation for a method that is already defined and/or implemented in its parent class or one of its parent classes.

Can we override a function?

Note: Only the functions that the derived class inherited from the base class can be overridden. Let's understand this concept with the help of a scenario. If the base class has a public member function, say, myfunc , then we can override the member function myfunc in the' derived' class.


1 Answers

From Overloadable Operators, the following operators can be overloaded:

  • Unary: +, -, !, ~, ++, --, true, false
  • Binary: +, -, *, /, %, &, |, ^, <<, >>
  • Comparison: ==, !=, <, >, <=, >=

And these operators cannot be overloaded:

  • Logical: &&, ||
  • Array Indexing: []
  • Cast: (T)x
  • Assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
  • Others: =, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof

Also, comparison operators need to be overloaded in pairs, if you overload one, you must overload the other:

  • == and !=
  • < and >
  • <= and >=
like image 63
Soner Gönül Avatar answered Sep 18 '22 19:09

Soner Gönül