C# and some OOP Flashcards

1
Q

BaseClass Vs Abstract Vs Interface vs Virtual

A

Base class - You can inherit from a baseclass and get all its methods and properties.

Abstract class - All the methods are abstract. The inheriting class needs to implement them.

Virtual Methods - Base class can have its own implementation that may be overriden by the inheriting class. So your base class can have methods that are avalailable and its own implementation and the inheriting class can use the regular methods in the base class but needs to override the virtual methods.

Use an abstract class if you have some functionality that you want it’s subclasses to have. For instance, if you have a set of functions that you want all of the base abstract class’s subclasses to have.

You can’t have a non abstract class with abstract methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is static and why use it?

A

Static means there is only one copy of a static member.

it does not need to be instantiated. So if you have a class with static variable you can use it like

MyClass.StaticVariableExample

If the static keyword is applied to a class, all the members of the class must be static.

Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.

Static functions are helpful as they do not rely on an instantiated member of whatever class they are attached to. So helper funtion type stuff.

Purists might argue that static is an abomination. Pragmatists might argue that it fills a gaping hole in the “everything is an object” abstraction, allowing you to call utility methods for which it doesn’t make sense to instantiate a new object just to call them. The canonical example of this is the System.Math class. (This is a static class)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

In short what is a singleton and why is it used?

A

A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.

It’s useful in many scenarios such as creating dialog boxes, handling registry settings, managing thread pools, logging, caching, configuration settings, and managing database connections

https://csharpindepth.com/Articles/Singleton

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the differences between Singleton and Static implementations.

A

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that’s less common, in my experience), so you can pass around the singleton as if it were “just another” implementation.

Because Singletons can be instantiated, and static not:

  1. Singletons can implement interfaces
  2. Singletons can be passed as parameters
  3. Singletons can have their instances swapped out (such as for testing purposes)
  4. Singletons can be handled polymorphically, so there may exist multiple implementations

**.net 7 does support static interfaces **

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the protected access modifier and why use it?

A

Access is limited to the containing class or types derived from the containing class.
Struct members cannot be protected because the struct cannot be inherited.

Meaning, you cannot access the protected member by creating an instance of the base class and accessing it. You will get an error.

While elements declared as private can be accessed only by the class in which they’re declared, the protected keyword allows access from sub-classes and members of the same package.

By using the protected keyword, we make decisions about which methods and fields should be considered internals of a package or class hierarchy, and which are exposed to outside code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What, why and how of singleton.

A

What?
1. A singleton is a class which only allows a single instance of itself to be created
2. Singletons don’t allow any parameters to be specified when creating the instance - otherwise a second request for an instance but with a different parameter could be problematic!

Why?
1. Common use-cases for the singleton design pattern include factories, builders, and objects that hold program state.
2. Its commonly used for something like a logger class.
3. It’s used for configuration, management, caches, or other things that you’re not going to have multiple of.

Why is it considered bad?
https://stackoverflow.com/questions/137975/what-are-drawbacks-or-disadvantages-of-singleton-pattern/138012#138012
http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

How?
1. A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn’t known until runtime.
2. The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
3. A static variable which holds a reference to the single created instance, if any.
4. A public static means of getting the reference to the single created instance, creating one if necessary.

Fully lazy instantiation
Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class’s private members, the reverse is not true, hence the need for instance to be internal here. That doesn’t raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Lazy<T>
If you’re using .NET 4 (or higher), you can use the System.Lazy<T> type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

In Java
~~~
// Java code to explain double check locking
public class GFG
{
// private instance, so that it can be
// accessed by only by getInstance() method
private static GFG instance;

private GFG()
{
// private constructor
}

public static GFG getInstance()
{
if (instance == null)
{
//synchronized block to remove overhead
synchronized (GFG.class)
{
if(instance==null)
{
// if instance is null, initialize
instance = new GFG();
}

  }
}
return instance;   } } ~~~
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are global variables and how do they relate to a Singleton?

A
  • In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program
  • In C# you cannot define true global variables (in the sense that they don’t belong to any class). This being said, the simplest approach that I know to mimic this feature consists in using a static class.
  • In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a sealed class?

A

Sealed classes are used to restrict the users from inheriting the class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is your experience in terms of dependecy in jection vs singleton?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the lifecycle of a .net api and its objects?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the protected internal access modifier?

A

The protected internal keyword combination is a member access modifier. A protected internal member is accessible from the current assembly or from types that are derived from the containing class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is an assemply in C# and how does it differ from a namespace?

A

Namespaces affect name resolution only. Namespaces do not imply any sort of storage, nor do namespaces determine which DLLs contain your code. Namespaces allow you to group related things together under a logical name even though they may physically reside in different DLLs.

An assembly is basically just a DLL or EXE file. It contains IL code and type information that describes the code in that DLL or EXE. It can contain a lot of other stuff too, but for starters just think of it as a DLL.

You put your code into a particular assembly by compiling your code into a project (csproj) that produces the DLL or EXE.

C# is a compiled language. This means that when a developer creates C# source files, those files need to be compiled before they can run. You can not write a C# file, and then run that file or combination of files like you can with say a JavaScript or PHP file. This is where assemblies come into play for a compiled language. Assembly files are the result of the C# compiler reading in human readable C# source files, and then producing a file the application can use. In fact a C# program will often consist of many assembly files working together.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Say whether each of these access modifiers are accessbile in the same or other assemply by declard, other or derived classes.
1. Private
2. Public
3. Protected
4. Internal
5. Protected Internal
6. Private Protected

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is mscorelib.dll

A

These types of files are used often for code reuse. The .NET Framework is a great example of code reuse. Common classes like Console and DateTime in .NET live inside an assembly the .NET framework provides named mscorlib.dll.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between a .exe and .dll

A

These types of files are used often for code reuse. The .NET Framework is a great example of code reuse. Common classes like Console and DateTime in .NET live inside an assembly the .NET framework provides named mscorlib.dll.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are the 4 Pillars of OOP?

A
17
Q

What is SOLID?

A
18
Q

How does Visual Studio decide what to build for an assemly?

A

Visual Studio has a bunch of options that get configured based on the type of project you choose. The assembly name is the same as the project name, so in this case it is Stocks.

The extension given to the assembly is controlled by the Output type setting. For either the Windows Application or Console Application, we will get that .exe extension. If we choose the Class Library option, the assembly would not longer get an .exe extension but instead a .dll extension.

19
Q

What is the difference between ADO.Net, OLEDB, ODBC and SQLClient?

A

ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data sources exposed through OLE DB and ODBC.

System.Data.SQLClient
* Can only be used for connecting to SQL Server 2000 and later. But you will get optimal performance when connecting to those databases.

System.Data.OledbClient
* OLE DB (Object Linking and Embedding, Database) is an API designed by Microsoft that allows accessing data from a variety of sources in a uniform manner1. It provides a uniform way to access various relational and non-relational data2. OLE DB interacts with SQL-based datasources through the ODBC driver layer3.
* Can be used to connected to SQL 6.5
* OLEDBClient gives you ability to connect to other database like ORALCE or Access. But for working with SQL Server you will get better performance using SQLClient.
* Note: For connecting to ORALCE Microsoft also has ORACLEClient.

System.Data.ODBCClient
* Provides connection to legacy databases ( e.g. MS Access 97) using ODBC drivers.*

**The big differentiators between SqlClient and OleDbClient (and OdbcClient too) are:
**
* SQlClient is managed (.NET). OleDbClient is a .NET wrapper of an unmanaged OLE DB provider
* SqlClient only works with SQL Server. OleDbClient can use any relational DBMS that has an OLE DB driver
* SqlClient is included with .NET. OleDbClient requires a separately installed OLE DB driver (although one could use the legacy SQLOLEDB provider that ships with windows).
* Always use SqlClient for SQL Server data access. It is also best to use a managed provider for other DBMS products when one is available. OleDbClient or OdbcClient should are intended to be used in .NET apps only when a suitable managed provider is not available.

20
Q

What is meant by Managed vs Unmanaged in .net?

A
  • In .NET, “managed” refers to anything within the .NET sandbox, which includes all .NET Framework classes.
  • “Unmanaged” refers to anything that is returned to you through calls to Win32 API functions1.
  • Managed resources are those that are pure .NET code and managed by the runtime and are under its direct control.
  • Unmanaged resources are those that are not 1. Examples of unmanaged resources include file handles, pinned memory, COM objects, database connections, etc 1.
21
Q

Explain Inheritence and when to use it?

A
  • Inheritence is not “code sharing”
  • It is a “its-a” relationship.
  • Needs to share common logic - not just properties or method names, but actual logic.
  • Sharing only properties or method signatures is not enough.

To inherit from a base class you simply write

public class CarRental: RentalVehicle
{
}
22
Q

What is the purpose of using disposables in C#?

A
  • The purpose is to free up unmanaged resources.
  • Unmanaged resources are things that arent managed by the .net framework like database connections etc.
  • Normally the Dispose method is used when the object holds pointers to some unmanaged resources and provides a mechanism to deterministically release those resources.
  • There are other reasons for implementing Dispose, for example, to free memory that was allocated, remove an item that was added to a collection, or signal the release of a lock that was acquired.
  • Normally garbadge collection cleans up memory etc, but it does NOT clean up unmanaged resources.
  • You can imagine for example that sql has only a specific number of connections in its connection pool and if your application does not dispose them it will run out of resour es.
  • To help ensure that resources are always cleaned up appropriately, a Dispose method should be idempotent, such that it’s callable multiple times without throwing an exception. Furthermore, subsequent invocations of Dispose should do nothing.
23
Q

Write an example of a disposable implementation.

A
public class Dog : MammalBase, IDisposable, IPet
    {
        public string Food { get; set; }

        private bool _disposed = false;

        //If you want all mammals to be Disposable, the base class should implement the IDisposable interface.
        public void Dispose()
        {
            //check if the dispose method has been called already
            //the dispose method must be idempotent to ensure that resources are always cleaned up effectively.
            if (!_disposed){
                //code to dispose resources would go here.
                Console.WriteLine("Disposing Dog resources...");
                _disposed = true;
            }
        }
    }
24
Q

What is the difference between Throw and Throw ex?

A

throw ex resets the stack trace (so your errors would appear to originate from HandleException)

throw doesn’t - the original offender would be preserved.

25
Q

Is an object a reference or value type?

A

Reference type. Its default is NULL.

26
Q

What is the difference between a reference or value type?

A

Your examples are a little odd because while int, bool and float are specific types, interfaces and delegates are kinds of type - just like struct and enum are kinds of value types.

I’ve written an explanation of reference types and value types in this article. I’d be happy to expand on any bits which you find confusing.

The “TL;DR” version is to think of what the value of a variable/expression of a particular type is. For a value type, the value is the information itself. For a reference type, the value is a reference which may be null or may be a way of navigating to an object containing the information.

For example, think of a variable as like a piece of paper. It could have the value “5” or “false” written on it, but it couldn’t have my house… it would have to have directions to my house. Those directions are the equivalent of a reference. In particular, two people could have different pieces of paper containing the same directions to my house - and if one person followed those directions and painted my house red, then the second person would see that change too. If they both just had separate pictures of my house on the paper, then one person colouring their paper wouldn’t change the other person’s paper at al

http://jonskeet.uk/csharp/references.html

27
Q

How to write an extension method for the string class

A

static decimal ToDecimal(this string str)
{
return Decimal.Parse(str, CultureInfo.CurrentCulture);
}