C
C#11mo 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
larvaOP11mo 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
Angius11mo ago
Correct
larva
larvaOP11mo ago
but you cant have catch and finally without try
Kouhai
Kouhai11mo ago
You can have
try
{
}
catch
{
}
finally
{
}
try
{
}
catch
{
}
finally
{
}
larva
larvaOP11mo 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
Angius11mo ago
You can always try and see
MODiX
MODiX11mo 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
larvaOP11mo 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
Angius11mo ago
The easiest way to check is... try Use $csharprepl $repl
MODiX
MODiX11mo 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
Angius11mo ago
Or go to #bot-spam and use $eval
MODiX
MODiX11mo 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
larvaOP11mo ago
$csharprepl
Angius
Angius11mo ago
Or use Sharplab
larva
larvaOP11mo 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
Angius11mo ago
$tias
Joschi
Joschi11mo 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
larvaOP11mo ago
is there an online compiler
Joschi
Joschi11mo ago
Like Sharplap or one of the other recommendations by ZZZZZZZZZ
Angius
Angius11mo ago
I prefer the terminal repl, but yeah, Sharplab is an online option
Joschi
Joschi11mo ago
There are multiple: dotnetfiddle, replit, sharplab apperantly can run code too somehow.
Angius
Angius11mo ago
Or just install .NET 8 SDK locally, install VS or VS Code, and go to town ¯\_(ツ)_/¯
Joschi
Joschi11mo 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
larvaOP11mo 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
Joschi11mo ago
Yes that sounds about right. Do you know under which conditions a method can be marked abstract in C#?
larva
larvaOP11mo ago
it doesnt have a body joschi what happened to ur colour 😦
Joschi
Joschi11mo ago
My color?
larva
larvaOP11mo ago
anyway continue under which conditions
Joschi
Joschi11mo 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
larvaOP11mo 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
Joschi11mo ago
Yes
larva
larvaOP11mo ago
another question you know the may be null error
Joschi
Joschi11mo ago
Let's keep at your original question for a second. Can an abstract class implement interfaces?
larva
larvaOP11mo ago
hmmm they both do the same song thing so i would say yes is that correct guess
Joschi
Joschi11mo ago
Yes that's correct.
larva
larvaOP11mo ago
interfaces cant do : classname right only classes can implement interface not the other way around
Joschi
Joschi11mo ago
No an interface cannot inherit from a class
larva
larvaOP11mo ago
ok can it inherit from another interface
Kouhai
Kouhai11mo ago
An interface can implement another interface So
internal interface InterfaceA
{}
internal interface InterfaceB : InterfaceA
{}
internal interface InterfaceA
{}
internal interface InterfaceB : InterfaceA
{}
larva
larvaOP11mo ago
ok thats good to know is that all when it comes to intefaces i cant declare smth static inside an interface
Kouhai
Kouhai11mo ago
In C# 11 and .NET 8 you can
larva
larvaOP11mo ago
damn
Joschi
Joschi11mo ago
There are also default implementations. But I think they are a bit frowned upon.
larva
larvaOP11mo ago
yeah dw my professor wont bring them
Kouhai
Kouhai11mo ago
You can do
public interface InterfaceA
{
public static bool IsStatic() => true;
}
public interface InterfaceA
{
public static bool IsStatic() => true;
}
larva
larvaOP11mo ago
her slides from 2009 ok good to know so yeah this is all when it comes to intefaces
Kouhai
Kouhai11mo ago
Yes, pretty much
larva
larvaOP11mo 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
Joschi11mo ago
Could you give an example?
larva
larvaOP11mo 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
Joschi11mo ago
$code
MODiX
MODiX11mo 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
larvaOP11mo 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
Joschi11mo 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
larvaOP11mo 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
Joschi11mo 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
larvaOP11mo ago
ok
Kouhai
Kouhai11mo 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
larvaOP11mo ago
ok so the class errorcodeexception needs to first have a property like that to justify using when
Joschi
Joschi11mo 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
Kouhai11mo 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
larvaOP11mo ago
cause its abstract it needs to be implemented but the 2nd one isnt?
Joschi
Joschi11mo 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
larvaOP11mo ago
ok
Kouhai
Kouhai11mo 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
larvaOP11mo ago
lol my version is c 10 i cant update it rn power outage barely any internet
larva
larvaOP11mo 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
Joschi11mo ago
Could you send a full example, where you face the issue and can't resolve it?
larva
larvaOP11mo ago
if (employee!=null){
salary = employee.basesalary;
if (employee!=null){
salary = employee.basesalary;
ok let me bring you
Kouhai
Kouhai11mo 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
larvaOP11mo ago
true
larva
larvaOP11mo ago
No description
larva
larvaOP11mo 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
Kouhai11mo 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
Joschi11mo ago
No that's not why. What does the error tell you if you remove the const?
larva
larvaOP11mo ago
No description
larva
larvaOP11mo ago
message is not null here why he wants it to be null
Kouhai
Kouhai11mo ago
That's different It's not that it wants null
Joschi
Joschi11mo ago
That is not the error. The Error is the line below
Kouhai
Kouhai11mo ago
It's first saying, that here message field is 100% not null
larva
larvaOP11mo ago
ok but if i remove the text then it will say it may be null right if i dont initialize it
Kouhai
Kouhai11mo ago
No, you can call the base consturctor for Exception without passing any message
larva
larvaOP11mo ago
yeah
Joschi
Joschi11mo ago
But your error there has nothing to do with nullability
larva
larvaOP11mo ago
damn fr? thought it was ok why does const remove it
Joschi
Joschi11mo ago
Read the full message. What does it tell you below "message is not null here"?
larva
larvaOP11mo ago
object reference required
Kouhai
Kouhai11mo ago
Basically what's happening is this message is an instance field right?
larva
larvaOP11mo ago
true
Kouhai
Kouhai11mo ago
A constructor creats the instance
larva
larvaOP11mo ago
so i need to use object.message to use it right
Kouhai
Kouhai11mo 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
larvaOP11mo ago
not quite understanding
Kouhai
Kouhai11mo 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
larvaOP11mo 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
Kouhai11mo ago
Yes, that's correct So where does MyStatic "live", it lives on the type itself right? @Gonzo
larva
larvaOP11mo ago
Yeah it's not an instance It's not tied to a specific object
Kouhai
Kouhai11mo ago
Exactly👍 When you make a field const It also lives on the type itself
larva
larvaOP11mo ago
Oooh Thanks hello another question i have are null errors
Kouhai
Kouhai11mo ago
I assume you mean warnings?
larva
larvaOP11mo 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
Kouhai11mo 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
Angius11mo 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
larvaOP11mo ago
how do i guarantee 100% my code is free from null errors do checks for null using if?
Joschi
Joschi11mo 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
Angius11mo 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
larvaOP11mo 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
Angius11mo ago
Nowadays, you would use pattern matching animal is Dog
MODiX
MODiX11mo 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
larvaOP11mo ago
No description
larva
larvaOP11mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ there is no relationship between machinery and buildings would this output exactly how i would want it
Angius
Angius11mo ago
They both implement IAssets though, don't they?
MODiX
MODiX11mo 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
larvaOP11mo ago
yes they both implement them
Angius
Angius11mo 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
larvaOP11mo ago
will this avoid exception errors i want to see what what will avoid exception
Angius
Angius11mo 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
larvaOP11mo ago
if i want to test methods then i will do lets sa b.Genericmethod(); right?
Angius
Angius11mo ago
Yep
larva
larvaOP11mo ago
is there a way to use as like this tho since as will never throw exceptions
Angius
Angius11mo 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
larvaOP11mo ago
No description
larva
larvaOP11mo ago
is this a correct implementation for as
Angius
Angius11mo ago
Close, m2 should be of type Machinery? (remember how as can return null?) Same for b2, should be Buildings?
larva
larvaOP11mo ago
ok so just do the ? at the end to i guess give the fact that it could be nullable
Angius
Angius11mo ago
Yep T? is a way of saying T or null
larva
larvaOP11mo ago
its like saying a territary operator where the true output is T and false output is null
Angius
Angius11mo ago
Ternary, but yeah, I guess you can look at it that way
larva
larvaOP11mo 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
Angius11mo ago
Access what?
larva
larvaOP11mo ago
if i enter an x less than 0 will it access the first catch only or is my implementation incorrect
Angius
Angius11mo ago
Try and see
larva
larvaOP11mo 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
Angius11mo ago
$vscode
MODiX
MODiX11mo 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
Angius11mo ago
Make sure you install the appropriate plugins Or better yet, that you install Visual Studio 2022 instead of VS Code
Joschi
Joschi11mo ago
Or if you are a student you can get all JetBrains IDEs for free.
larva
larvaOP11mo ago
No description
larva
larvaOP11mo ago
Shouldnt first 2 outputs be m1 method in class B
Want results from more Discord servers?
Add your server