Monday, May 4, 2026

C# difference between a cast and using "as" operator

In C#, the primary difference between a cast (T)obj and the as operator is how they handle failed conversions: a cast throws an exception, while the as operator returns null. 
Key Differences
Feature Direct Cast (T)objas Operator obj as T
Failure ResultThrows InvalidCastExceptionReturns null
Type SupportWorks with any type (Reference & Value)Works only with Reference or Nullable types
User ConversionsExecutes User-defined conversionsIgnores user-defined conversions
PerformanceCan be slower if it fails (exception overhead)Generally faster for testing types safely
When to Use Each
  • Use a Direct Cast (T)obj when you are certain the object is of the target type. If it fails, it indicates a bug, and throwing an exception immediately is safer than propagating bad data.
  • Use the as Operator when you are not sure of the type and want to branch your logic based on the result. This requires a null-check immediately following the operation.
  • Modern Alternative: In newer versions of C#, you can use the is operator with pattern matching to check and cast in a single step:
    csharp
    if (obj is MyType myTypedObj) 
    {
        // Use myTypedObj here
    }



Key Differences at a Glance
Feature Cast Expression (Type)objas Operator obj as Type
Failure ResultThrows InvalidCastExceptionReturns null
Supported TypesAll compatible types (reference & value)Reference types or nullable value types only
Custom ConversionsInvokes user-defined conversion operatorsIgnored; only reference, boxing/unboxing conversions
Best Intent"I expect this to be this type; error if not.""I'm not sure; let me check and handle it."






Modern Pattern Matching: "is"
In older C#, you often had to perform two steps: check the type with is and then cast it. Today, you can do this in one line: 
csharp
// The Modern Way: Pattern Matching (C# 7.0+)
if (obj is MyType myVar) 
{
    // myVar is already cast and ready to use here
    Console.WriteLine(myVar.SomeProperty);
}
Key Advantages over "as" and Casts
  • Safety & Cleanliness: It combines the check and the cast into a single expression, reducing code bloat and the risk of a NullReferenceException that can happen if you forget a null check after using as.
  • Better than "as" for Value Types: The as operator only works with reference or nullable types. Pattern matching works seamlessly with both value types (like int) and reference types (like string).
  • Expressiveness: Modern is supports complex patterns like logical patterns (not, and, or) and property patterns (checking internal object properties).
    csharp
    // C# 9.0+ logical patterns
    if (input is not null) { ... }
    
    // Complex matching
    if (shape is Rectangle { Width: > 10 } r) { ... }
    

  • Avoids Double Checking: Unlike the old if (obj is MyType) { var x = (MyType)obj; }, pattern matching only performs the runtime type check once, making it more efficient. 
Recommendations
  • For null checks: Use if (obj is null) or if (obj is not null). This is safer than == null because it ignores any operator overloading that might change the result.
  • For general type-casting: Prefer is pattern matching over as whenever you need to use the variable immediately after the check. 






 

Of Virtual and Override in C# (Back to Basics)

 *Declaring derived class variable as object of base class is not allowed. 

DerivedClass dc = new ParentClass(); //compiler gives error.

DerivedClass dc = (DerivedClass)new ParentClass(); //compiler allows, but runtime gives InvalidCast Exception


*Declaring base class variable as derived class is allowed. 

ParentClass pc = new DerivedClass();

In this case: 

*Derived Object is created and it remains on Heap. 

*However any access to the pc variable always refers to properties or methods of parent class

*EXCEPT for virtual/override combination. 

*Only for overridden methods in this case, the methods of derived class are called. 

*FOR ANY METHODS NOT SATISFYING THE FOLLOWING FOUR CONDITIONS, ALWAYS BASE CLASS IMPLEMENTATIONS ARE CALLED.


THUS TO TRIGGER RUNTIME POLYMORPHISM:

*The method/property in parent class must be declared with "virtual" keyword

*The same method/property in child class must be declared with "override" keyword

*The variable(LHS) must of parent type 

*The object(RHS) must be of child type




MUTLIPLE HIERACRHY: 

Consider the case of Grand Parent, Parent and Child class. We can have

GrandParent gp = new Child(); 


In this case if a method is declared as virtual in GP, and it is overridden ACROSS ALL CLASSES IN 

THE CHAIN, THEN THE CHILD CLASS (RHS CLASS) METHOD IS CALLED. 

BUT IF THE CHAIN IS BROKEN SOMEWHERE BY METHOD HIDING, THE GP (base class on LHS) METHOD IS CALLED.

Note that the only classes in consideration are either RHS or LHS classes, nobody else in the hierarchy.




*Why properties can be declared as virtual and why it is a good practice to override them: 

*Properties are also methods ( getter/setter) hence they are also part of virtual/override logic

*Properties also should be overridden to clear any confusion. Consider the case:

*Base class declares a property as virtual and it declares two methods such that:

- both methods use this property for their calculations

- one of the two methods is virtual and other is not

*Now derived class overrides the virtual method and puts it own logic into it

*BUT derived class redeclares the property and forgets to use "override" keyword.

*Now Base baseClass  = new Derived(); declaration is done. 

*Now the memory representation of baseClass contains two versions of the property: 

*one for base class

*second for derived class, because its redeclaration shadows original base version.

*So the overridden method refers to the property value of derived class

*And the non-overridden method uses the value of property from base class.

THIS IS THE CONFUSION CAUSED. HENCE IT IS ALWAYS A GOOD PRACTIVE TO OVERRIDE VIRTUAL PROPERTIES ALSO.



Consider a hierarchy of multiple classes. Some of them  use override , some of them do not. 

When does the virtual hierarchy ends ? 

*in c#, any overridden method is implicitly virtual. Any override method can again be 

overridden by child class. In this case, the virtual override mechanism always looks for the applicable LAST override in the hierarchy. 




A method is declared as "virtual" in base class. What keywords are allowed for it in derived class ? 

"new" -> suppresses warning "hides the inherited member" 

"virtual" -> hides the parent method, declares new virtual method, warning - "hides the inherited member"

"new virtual" -> hides parent method, declares new virtual method, warning suppressed

"override" -> overrides parent method, "new" or "virtual" are not allowed with this

YOU CANNOT USE "new" or "virtual" in combination with "override" keyword.



isn't it a compile time error to have override without virtual in the base class ?

Yes: It is a compile time error to use override keyword with a method that is not "virtual" in base class. 


When you declare a virtual function:

  • The compiler adds a hidden pointer inside the object → vptr
  • This pointer points to a table of function addresses → vtable



Wednesday, April 29, 2026

useful links

 


https://github.com/huggingface/cookbook/tree/main/notebooks/en  hugging face ai cookbooks 


https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/multiagent_rag_system.ipynb




https://huggingface.co/learn/cookbook/index

https://weaviate.io/blog/what-is-agentic-rag

https://www.tigerdata.com/learn/hnsw-vs-diskann



https://cloud.google.com/blog/topics/developers-practitioners/building-collaborative-ai-a-developers-guide-to-multi-agent-systems-with-adk

Comparing features of LangGraph vs CrewAI

LangGraph Orchestration vs CrewAI Orchestration The following table compares LangGraph and CrewAI orchestration across their menta...