C
C#10mo ago
larva

Exam Prep OOP(Constructors , Inheritance , interface , polymorphism , Exception Handling

topics i will be covering inheritance constructors static sealed for both methods and classes polymorphism interface Exception Handling Overload Override Abstract sorry for the the long list
141 Replies
larva
larva10mo ago
hello so lets start with exception handling so for try i only write the code which might cause an error for catch i write the type of error i expect to happen and what should i do when i encounter such a problem for finally i write what i want to pass regardless of errors or not try can have a catch but no finally and can have a finally but no catch is all of that correct
Angius
Angius10mo ago
Correct
larva
larva10mo ago
but you cant have catch and finally without try
Kouhai
Kouhai10mo ago
You can have
try
{
}
catch
{
}
finally
{
}
try
{
}
catch
{
}
finally
{
}
larva
larva10mo ago
also i have another question if i did 3 catch cases it will only choose one and skip the others even if they are the same catch exception
Angius
Angius10mo ago
You can always try and see
MODiX
MODiX10mo ago
Angius
REPL Result: Failure
try {
throw new Exception("Hello");
} catch(Exception e) {
Console.WriteLine(e.Message);
} catch(Exception e) {
Console.WriteLine(e.Message);
} catch(Exception e) {
Console.WriteLine(e.Message);
}
try {
throw new Exception("Hello");
} catch(Exception e) {
Console.WriteLine(e.Message);
} catch(Exception e) {
Console.WriteLine(e.Message);
} catch(Exception e) {
Console.WriteLine(e.Message);
}
Exception: CompilationErrorException
- A previous catch clause already catches all exceptions of this or of a super type ('Exception')
- A previous catch clause already catches all exceptions of this or of a super type ('Exception')
- A previous catch clause already catches all exceptions of this or of a super type ('Exception')
- A previous catch clause already catches all exceptions of this or of a super type ('Exception')
Compile: 368.365ms | Execution: 0.000ms | React with ❌ to remove this embed.
larva
larva10mo ago
how do i use this what if i dide exception first then smaller exception later it wouldnt cause an error right but only the first catch would activate
Angius
Angius10mo ago
The easiest way to check is... try Use $csharprepl $repl
MODiX
MODiX10mo ago
GitHub
GitHub - waf/CSharpRepl: A command line C# REPL with syntax highlig...
A command line C# REPL with syntax highlighting – explore the language, libraries and nuget packages interactively. - GitHub - waf/CSharpRepl: A command line C# REPL with syntax highlighting – expl...
Angius
Angius10mo ago
Or go to #bot-spam and use $eval
MODiX
MODiX10mo ago
Compile C# code in #bot-spam, use !eval Example:
!eval for(int i = 0; i < 4; i++) Console.WriteLine(i);
!eval for(int i = 0; i < 4; i++) Console.WriteLine(i);
larva
larva10mo ago
$csharprepl
Angius
Angius10mo ago
Or use Sharplab
larva
larva10mo ago
if i write a code after catch not a finally but a code after catch and catch has been caught does it execute that code too
Angius
Angius10mo ago
$tias
Joschi
Joschi10mo ago
You should really look for some environment to run C# snippets and just test those questions. If you get stuck or don't know how to do that, someone here is probably willing you to help getting started.
larva
larva10mo ago
is there an online compiler
Joschi
Joschi10mo ago
Like Sharplap or one of the other recommendations by ZZZZZZZZZ
Angius
Angius10mo ago
I prefer the terminal repl, but yeah, Sharplab is an online option
Joschi
Joschi10mo ago
There are multiple: dotnetfiddle, replit, sharplab apperantly can run code too somehow.
Angius
Angius10mo ago
Or just install .NET 8 SDK locally, install VS or VS Code, and go to town ¯\_(ツ)_/¯
Joschi
Joschi10mo ago
Which is probably the best way to go about that in the long term, since you will need that anyways if you wanna work with C# in some capacity.
larva
larva10mo ago
thanks i learned alot hello can someone explain interfaces so interface is like a contract i put in it abstract unimplemented methods and a class can have multiple interfaces implemented and the same interface can be implemented by other classes is that correct but what i want to know can the class leave the methods as abstract
Joschi
Joschi10mo ago
Yes that sounds about right. Do you know under which conditions a method can be marked abstract in C#?
larva
larva10mo ago
it doesnt have a body joschi what happened to ur colour 😦
Joschi
Joschi10mo ago
My color?
larva
larva10mo ago
anyway continue under which conditions
Joschi
Joschi10mo ago
No that is what it means to be abstract. My question would be: "Is the following valid C# code?"
c#
internal class MyClass: ISomeInterface
{
public abstract int MyMethod();
}
c#
internal class MyClass: ISomeInterface
{
public abstract int MyMethod();
}
larva
larva10mo ago
no class isnt abstract if i want to implement the method then the class either has to be abstract or add body to the method is this correct
Joschi
Joschi10mo ago
Yes
larva
larva10mo ago
another question you know the may be null error
Joschi
Joschi10mo ago
Let's keep at your original question for a second. Can an abstract class implement interfaces?
larva
larva10mo ago
hmmm they both do the same song thing so i would say yes is that correct guess
Joschi
Joschi10mo ago
Yes that's correct.
larva
larva10mo ago
interfaces cant do : classname right only classes can implement interface not the other way around
Joschi
Joschi10mo ago
No an interface cannot inherit from a class
larva
larva10mo ago
ok can it inherit from another interface
Kouhai
Kouhai10mo ago
An interface can implement another interface So
internal interface InterfaceA
{}
internal interface InterfaceB : InterfaceA
{}
internal interface InterfaceA
{}
internal interface InterfaceB : InterfaceA
{}
larva
larva10mo ago
ok thats good to know is that all when it comes to intefaces i cant declare smth static inside an interface
Kouhai
Kouhai10mo ago
In C# 11 and .NET 8 you can
larva
larva10mo ago
damn
Joschi
Joschi10mo ago
There are also default implementations. But I think they are a bit frowned upon.
larva
larva10mo ago
yeah dw my professor wont bring them
Kouhai
Kouhai10mo ago
You can do
public interface InterfaceA
{
public static bool IsStatic() => true;
}
public interface InterfaceA
{
public static bool IsStatic() => true;
}
larva
larva10mo ago
her slides from 2009 ok good to know so yeah this is all when it comes to intefaces
Kouhai
Kouhai10mo ago
Yes, pretty much
larva
larva10mo ago
what is the when clause in catch blocks doesnt catch automatically catch an exception if it occurs whats the reason for the when
Joschi
Joschi10mo ago
Could you give an example?
larva
larva10mo ago
ok try {int x = Convert.Toint32(Console.Readline());} catch(format exception fe) { console.writeline("hi); if i enter hello in the x i will get an exception format exception FormatException so the catch will be triggered
Joschi
Joschi10mo ago
$code
MODiX
MODiX10mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
larva
larva10mo ago
cs try {int x = Convert.Toint32(Console.Readline());} catch(format exception fe) { console.writeline("hi);
cs try {int x = Convert.Toint32(Console.Readline());} catch(format exception fe) { console.writeline("hi);
Joschi
Joschi10mo ago
Just as an example for statics on interfaces and how to use them.
c#
internal interface IHaveStaticMembers
{
public static abstract void StaticMethod();
public static abstract int StaticInt { get; }
}

internal static class MyClass
{
public static void AMethod<T>() where T: IHaveStaticMembers
{
T.StaticMethod();
var someVar = T.StaticInt;
}
}
c#
internal interface IHaveStaticMembers
{
public static abstract void StaticMethod();
public static abstract int StaticInt { get; }
}

internal static class MyClass
{
public static void AMethod<T>() where T: IHaveStaticMembers
{
T.StaticMethod();
var someVar = T.StaticInt;
}
}
larva
larva10mo ago
thanks anything in interfaces are automatically static and abstract though right except when i do default so static and abstract in interfaces are redundant correct?
Joschi
Joschi10mo ago
No nothing in an interface is automatically static! They are implied to be abstract. But you explicitely need to add abstract for static members.
larva
larva10mo ago
ok
Kouhai
Kouhai10mo ago
You would mostly use when clause when you're doing something like this Let's say you have an exception that has a property "ErrCode" You can do
try
{
// The code that might throw an exception
}
catch(ErrorCodeException ex) when (ex.ErrCode == 0xC00007b)
{
}
catch(ErrorCodeException ex) when (ex.ErrCode == 0xddddddd)
{
}
try
{
// The code that might throw an exception
}
catch(ErrorCodeException ex) when (ex.ErrCode == 0xC00007b)
{
}
catch(ErrorCodeException ex) when (ex.ErrCode == 0xddddddd)
{
}
larva
larva10mo ago
ok so the class errorcodeexception needs to first have a property like that to justify using when
Joschi
Joschi10mo ago
c#
internal interface IHaveStaticMembers
{
/// <summary>
/// This needs to be implemented by the class
/// </summary>
public static abstract int StaticInt { get; }

/// <summary>
/// This is a static on an interface, you don't need to implement it.
/// </summary>
public static int StaticIntOnTheInterface { get; } = 10;
}
c#
internal interface IHaveStaticMembers
{
/// <summary>
/// This needs to be implemented by the class
/// </summary>
public static abstract int StaticInt { get; }

/// <summary>
/// This is a static on an interface, you don't need to implement it.
/// </summary>
public static int StaticIntOnTheInterface { get; } = 10;
}
Kouhai
Kouhai10mo ago
Yeah you would need to "check" for something to justify using them So in that case we were checking for the value of ErrCode
larva
larva10mo ago
cause its abstract it needs to be implemented but the 2nd one isnt?
Joschi
Joschi10mo ago
No, the second one is not abstract. This is probably mostly because of older language limitations, where you could not have statics defined by an interface. Why don't you try to do the following: 1. Implement IHaveStaticMembers in a class. 2. Create a method that uses both members defined by IHaveStaticMembers.
larva
larva10mo ago
ok
Kouhai
Kouhai10mo ago
When you have a static abstract member in an interface, you have to implement it in the class that implements the interface When you don't have abstract, if the static member is a method, you HAVE to provide an implementation for it in the interface itself
larva
larva10mo ago
lol my version is c 10 i cant update it rn power outage barely any internet
larva
larva10mo ago
ok thanks now for another question if you guys want to chill its ok i asked a lot of questions you can answer this in your free times now why do i have may be null errors on string and objects and can checking for null remove all these errors like if (employee != null)
Joschi
Joschi10mo ago
Could you send a full example, where you face the issue and can't resolve it?
larva
larva10mo ago
if (employee!=null){
salary = employee.basesalary;
if (employee!=null){
salary = employee.basesalary;
ok let me bring you
Kouhai
Kouhai10mo ago
If you have for example this class
class User
{
public string Name {get;set;}
public User()
{ }
}
class User
{
public string Name {get;set;}
public User()
{ }
}
And we create an instance of the User class isn't it possible for Name to be null?
larva
larva10mo ago
true
larva
larva10mo ago
No description
larva
larva10mo ago
if i remove the const its an error ik why const means this cannot be changed so 0% of chance of it every getting modified to null
Kouhai
Kouhai10mo ago
Nullable reference types allows you to give the compiler a hint on whether it can expect this refenece instance to be null or not So
class User
{
public string? Name {get;set;}
public User()
{ }
}
class User
{
public string? Name {get;set;}
public User()
{ }
}
The ? after the type string gives the compiler a hint that yes, Name might be null So when you use it for example
var myuser = new User():
if(myuser.Name == "John")
{
}
var myuser = new User():
if(myuser.Name == "John")
{
}
The compiler would warn you that hey, it might be null
Joschi
Joschi10mo ago
No that's not why. What does the error tell you if you remove the const?
larva
larva10mo ago
No description
larva
larva10mo ago
message is not null here why he wants it to be null
Kouhai
Kouhai10mo ago
That's different It's not that it wants null
Joschi
Joschi10mo ago
That is not the error. The Error is the line below
Kouhai
Kouhai10mo ago
It's first saying, that here message field is 100% not null
larva
larva10mo ago
ok but if i remove the text then it will say it may be null right if i dont initialize it
Kouhai
Kouhai10mo ago
No, you can call the base consturctor for Exception without passing any message
larva
larva10mo ago
yeah
Joschi
Joschi10mo ago
But your error there has nothing to do with nullability
larva
larva10mo ago
damn fr? thought it was ok why does const remove it
Joschi
Joschi10mo ago
Read the full message. What does it tell you below "message is not null here"?
larva
larva10mo ago
object reference required
Kouhai
Kouhai10mo ago
Basically what's happening is this message is an instance field right?
larva
larva10mo ago
true
Kouhai
Kouhai10mo ago
A constructor creats the instance
larva
larva10mo ago
so i need to use object.message to use it right
Kouhai
Kouhai10mo ago
But doing this
: base(message)
: base(message)
Means call the base constructor before calling my constructor So the instance is still not "created" const makes message be on the type itself Hence why you can do
class MyClass
{
public const string MyConst = "Hello";
}
var v = MyClass.MyConst;
class MyClass
{
public const string MyConst = "Hello";
}
var v = MyClass.MyConst;
larva
larva10mo ago
not quite understanding
Kouhai
Kouhai10mo ago
Okay let's try something different
public MyClass
{
public static string MyStatic = "Hello";
}
public MyClass
{
public static string MyStatic = "Hello";
}
How would you access MyStatic
larva
larva10mo ago
If I am accessing it Inside myclass It would be MyStatic If it's in another class It would be MyClass.Mystatic Is this correct @Kouhai /人◕ ‿‿ ◕人\
Kouhai
Kouhai10mo ago
Yes, that's correct So where does MyStatic "live", it lives on the type itself right? @Gonzo
larva
larva10mo ago
Yeah it's not an instance It's not tied to a specific object
Kouhai
Kouhai10mo ago
Exactly👍 When you make a field const It also lives on the type itself
larva
larva10mo ago
Oooh Thanks hello another question i have are null errors
Kouhai
Kouhai10mo ago
I assume you mean warnings?
larva
larva10mo ago
yeah why do they warn me if smth may be null like i know bro its a data type which might be null like string or object whats the best way to avoid null errors just say if (objectname != null)?
Kouhai
Kouhai10mo ago
Can you show a code sample where it warns you, because it depends on the context whether you want to the reference type to be nullable or not
Angius
Angius10mo ago
Noll errors are usually not about "this can be null" but rather, "this can be null but you're not handling this eventuality" or "this can be null, but you're passing it somewhere where it cannot be null"
larva
larva10mo ago
how do i guarantee 100% my code is free from null errors do checks for null using if?
Joschi
Joschi10mo ago
Yes you want to make sure that nulls are always handled somehow. If possible gracefully, or you will run into null reference exceptions. Which can be really annoying and sometimes hard to reproduce.
Angius
Angius10mo ago
Nowadays, you would have nullable reference types enabled for the project So it shows you warnings whenever there is some issues with null And you have plenty of ways to deal with it. Starting with an if of course, through pattern matching, null-coalescing operator, null-conditional calls, all the way to more rare ways like null-forgiving operator or specific attributes
larva
larva10mo ago
sup guys if i want to use a method polymorphically i first have to check if the superclass has object type of the derived class for example
if(animal instanceof dog){
animale.move();
}
if(animal instanceof dog){
animale.move();
}
animal isnt the class its the reference to the object
Angius
Angius10mo ago
Nowadays, you would use pattern matching animal is Dog
MODiX
MODiX10mo ago
Angius
REPL Result: Success
class Animal {}
class Dog : Animal {}
Animal a = new Dog();
a is Dog
class Animal {}
class Dog : Animal {}
Animal a = new Dog();
a is Dog
Result: bool
True
True
Compile: 240.167ms | Execution: 24.841ms | React with ❌ to remove this embed.
larva
larva10mo ago
No description
larva
larva10mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ there is no relationship between machinery and buildings would this output exactly how i would want it
Angius
Angius10mo ago
They both implement IAssets though, don't they?
MODiX
MODiX10mo ago
Angius
REPL Result: Success
interface IFoo {}
class Bar : IFoo {}
IFoo a = new Bar();
a is Bar
interface IFoo {}
class Bar : IFoo {}
IFoo a = new Bar();
a is Bar
Result: bool
True
True
Compile: 277.841ms | Execution: 24.729ms | React with ❌ to remove this embed.
larva
larva10mo ago
yes they both implement them
Angius
Angius10mo ago
Then you can easily use pattern matching Pattern matching with a cast, even
IFoo thing = new Bar(); // Bar : IFoo

if (thing is Bar b) // `b` is of type `Bar` here, no longer `IFoo`
{
// ...
}
else if (thing is Quz q) // `q` is of type `Quz`, like above
{
// ...
}
IFoo thing = new Bar(); // Bar : IFoo

if (thing is Bar b) // `b` is of type `Bar` here, no longer `IFoo`
{
// ...
}
else if (thing is Quz q) // `q` is of type `Quz`, like above
{
// ...
}
larva
larva10mo ago
will this avoid exception errors i want to see what what will avoid exception
Angius
Angius10mo ago
Well, you are guaranteed that b here will be a Bar and not a Quz, so it will avoid exceptions connected to that
larva
larva10mo ago
if i want to test methods then i will do lets sa b.Genericmethod(); right?
Angius
Angius10mo ago
Yep
larva
larva10mo ago
is there a way to use as like this tho since as will never throw exceptions
Angius
Angius10mo ago
I guess you can use it similarly as will either cast to the desired type, or return null if it cannot So check for null and you're good
larva
larva10mo ago
No description
larva
larva10mo ago
is this a correct implementation for as
Angius
Angius10mo ago
Close, m2 should be of type Machinery? (remember how as can return null?) Same for b2, should be Buildings?
larva
larva10mo ago
ok so just do the ? at the end to i guess give the fact that it could be nullable
Angius
Angius10mo ago
Yep T? is a way of saying T or null
larva
larva10mo ago
its like saying a territary operator where the true output is T and false output is null
Angius
Angius10mo ago
Ternary, but yeah, I guess you can look at it that way
larva
larva10mo ago
Console.WriteLine("Hello, World!"); int x = Convert.ToInt32(Console.ReadLine()); try { if(x < 0) { throw new OutofBounds(); } if (x > 1000) { throw new OutofBounds(); }
} catch(OutofBounds ob) when ( x < 0) { Console.WriteLine("hi"); } catch(OutofBounds ob) when (x > 1000) { Console.WriteLine("Hello"); } hello will this code access
Angius
Angius10mo ago
Access what?
larva
larva10mo ago
if i enter an x less than 0 will it access the first catch only or is my implementation incorrect
Angius
Angius10mo ago
Try and see
larva
larva10mo ago
my visual code studio has a problem it doesnt debug tried on sharplab but it doesnt recognize try and catch only tryblock and some catchblock
Angius
Angius10mo ago
$vscode
MODiX
MODiX10mo ago
Follow the instructions here on getting started with DevKit for C# in VSCode: https://code.visualstudio.com/docs/csharp/get-started
Get started with C# and .NET in Visual Studio Code
Getting Started with C# and .NET Development in Visual Studio Code
Angius
Angius10mo ago
Make sure you install the appropriate plugins Or better yet, that you install Visual Studio 2022 instead of VS Code
Joschi
Joschi10mo ago
Or if you are a student you can get all JetBrains IDEs for free.
larva
larva10mo ago
No description
larva
larva10mo ago
Shouldnt first 2 outputs be m1 method in class B
Want results from more Discord servers?
Add your server