C# Questions

Ace your homework & exams now with Quizwiz!

What are ways to do a Thread Safe Singleton?

//Preferred public sealed class Singleton{ private static readonly Singleton instance = new Singleton(); private Singleton(){} public static Singleton Instance { get { return instance; } } } //Double checked locking public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } } //.net 4 Lazy One 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() { } }

What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?

32bit processes have 4GB and 64bit processes have 8TB. At any given time the data in virtual memory space might be stored in RAM, on disk, or both. All of this is totally transparent to all applications. Frequently accessed data will be kept in RAM with the remainder left on disk.

Here is a text box how do you bind the text to any DataContext? <TextBox />

<TextBox Text="{Binding Path=Text}" />

What is Single-Responsibility Principle?

A class should have one and only one reason to change, meaning that a class should have only one job.

Describe Abstraction

A class which can't be instantiated and sole purpose is to be inherited. Abstract methods are meant to either be used as default implementations or to be overridden. public abstract class Animal { public abstract void Speak(); } public class Cat : Animal { public override Speak(){ Meow; } }

Describe Quicksort

A comparison sort which uses small amounts of memory and is fast. It uses current element, wall, and a pivot. It breaks the list up by placing a wall, putting all elements less than the pivot left of the wall and all elements larger to the right and then placing the pivot on the wall. Worst Case Performance: O(n^2) Best Case Performance: O(n log n) Avg. Case Performance: O(n log n)

What is dependency injection and what are the advantages of using it.

A software design pattern that implements inversion of control for software libraries. Meaning essentially, that you are removing dependencies from within your code. There is a container that injects dependencies, instantiates objects, life cycle management. The best advantage is it makes testing easier, as in DI you usually register items/pass instances using an interface. More Reusable code . Also can load dlls at runtime.

What is Reflection?

A way to explore the structure of assemblies at run-time (discover which classes/resources/methods there are)

When should you use "code-behind in MVVM?

A: When the code only involves the View or WPF Controls in the View. B: When you need to implement events that do not support binding to ICommand.

What is the Adapter Design Pattern?

Adapter pattern is like using a three prong with a two prong outlet. Adapter will essentially make calls to different items. So Car interface drives forward, but you want say a Ostrich Car, it won't drive forward it will walk forward.

Option Explicit Option Strict Option Compare

All these options must appear in file before any source code statements. When Option Explicit On or Option Explicit appears in a file, you must explicitly declare all variables by using the Dim or ReDim statements. If you try to use an undeclared variable name, an error occurs at compile time. The Option Explicit Off statement allows implicit declaration of variables. Option Strict restricts implicit data type conversions to only widening conversions. Widening conversions explicitly do not permit any data type conversions in which data loss may occur and any conversion between numeric types and strings. The Option Compare statement specifies the string comparison method (Binary or Text). The default text comparison method is Binary. A Binary comparison compares the numeric Unicode value of each character in each string. A Text comparison compares each Unicode character based on its lexical meaning in the current culture.

Describe what an Interface is and how it's different from a Class.

An interface is a guideline that a class must implement, a contract. It has no executable code. Classes implement interfaces.

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Aspect-Oriented Aspect-oriented programming looks at how many components or pieces of a system might need to interact. The intersections of these pieces are what are important in AOP. "Crosscutting" is a slice across several units, all of which interact during some operation. Interface-Oriented Interface-oriented programming is a contract-based approach. Nether side of the interface cares how the other does its work, only that the two sides can communicate via an agreed-upon contract. WSDL-based web services are the prime example of this. Object-Oriented Object-Oriented programming is based on abstraction, encapsulation (data hiding), polymorphism and inheritance. Classes implement these concepts to build objects controlling or implementing a system.

Describe Merge Sort

Breaks up all items in the list into list of size one. Then combines the list into lists of size 2, in order. Then combines into 4 and so on. On the combine it will look at the first element of each, knowing that one will be the least element as they are already sorted. This technique is known as divide and conquer algorithm, it's big downfall is memory. Worst Case Performance: O(n log n) Best Case Performance: O(n log n) Avg. Case Performance: O(n log n)

What happens within an async function when an await is encountered?

C# async functions only execute up until the first await statement, then return to the caller. The function called by await is executed asynchronously, and the line after the await statement isn't signaled to execute until it's task completes. Keep in mind that within that time, control has already returned to the caller of the async function.

Create Table Example

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) )

How do you implement binding a button click to a method?

Create a class that implements ICommand, often called RelayCommand or RoutedCommand. Add an ICommand property to your ViewModel and instantiate the property using your ICommand implementation, RelayCommand or RoutedCommand.

What is the difference between an EXE and a DLL?

EXE: An executable file There is only single main entry When a system launches new exe, a new process is called The entry thread is called in context of the main thread of that process DLL: A Dynamic Link Library There are many entry points The system loads a DLL into the context of an existing thread

Conceptually, what is the difference between early-binding and late-binding?

Early binding determines execution path at compilation, late binding allows for dynamic execution at runtime.

Describe Encapsulation

Encapsulation is a term that is found in Object-Oriented paradigm and refers to keeping the data in private fields and modify it only through methods. Thus encapsulation may be seen as a way of achieving data hiding in object-oriented systems.

What is Dependency Inversion Principle?

Essentially the decoupling of software modules. A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend on details. Details should depend on abstractions.

What is Liskov Substitution Principle?

Every derived/subclass should be substitutable for their base/parent class. Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

What is the Decorator Design Pattern?

Extend old classes with new code. Abstract class created which takes old class, say LibraryItem (which can be a book or video). Then want to add Borrowable on top of that so it will inherit this abstract class and allow to add methods for that.

in MVVM what is INotifyPrepertyChanged used for?

For notifying any observer, usually a WPF control, that the property it is bound to has changed.

Name as many layout controls as you can.

Grid, DockPanel, Canvas, WrapPanel, StackPanel, UniformGrid

What does .NET use for Array Sort?

If the partition size is fewer than 16 elements, it uses an insertion sort algorithm. If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm. Otherwise, it uses a Quicksort algorithm.

Describe Inheritance

Inheritance allows a derived class to gain all the non-private data and behavior of the base class in addition to any other data or behaviors it defines for itself.

WPF: What is a Dependency Property?

Is a property system used by an object that inherits from the DependencyObject. Remember, a DP never really "has" a value, its value depends on various external factors. That's why they are called dependency properties. They have to registered (DependencyPropery.Register) and within the regesiter can be PropertyMetadata which can do things like set default, set a changed callback and a Coerce callback. There can also be a validate callback, which is boolean, throws an exception on false. These callbacks are all private, meaning they are called for each instance of the created from the class.

What is a virtual Method? Why use it?

It is a method whose behavior can be overridden only within an inheriting class by a method with the same signature. It allows for polymorphic behavior.

What is the GAC? What problem does it solve?

It is the Global Assembly Cache. Each computer on which the CLR is installed has a machine-wide code cache called the GAC. Assemblies deployed in the global assembly cache must have a strong name. A developer tool named "Global Assembly Cache tool" (Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. It provides us the way to overcome "DLL Hell" problem also.

What is the entry point for a WPF application?

It's in an autogenerated class called App.g.i.cs, a partial class of the App class.

What is MVVM?

MVVM is Model View ViewModel architectural pattern. It's great for WPF, since the ViewModel binds to View with WPF magic binding. It's separation of View and ViewModel is great, because you can change the whole view on a him, which happens early on in development.

What is Interface segregation Principle?

No client should be forced to depend on methods it does not use.

How many processes can listen on a single TCP/IP port?

Only one. If there was more than one process listening on the same port, then there would be no way of knowing which process incoming data was intended for.

What is a PID? How is it useful when troubleshooting a system?

PID stands for Process Identifier, a uniquely assigned integer that identifies a process in the operating system. In any system, applications use PID to identify the process uniquely. Also, it is used in diagnosing the problems with the process in Multi-Tasking systems.

Describe Polymorphism

Polymorphism allows the expression of some sort of contract, with potentially many types implementing that contract (whether through class inheritance or not) in different ways, each according to their own purpose. Code using that contract should not(*) have to care about which implementation is involved, only that the contract will be obeyed. (*) In the ideal case, anyway - obviously quite often the calling code has chosen the appropriate implementation very deliberately! I say: Animals, talk => Meow, Bark, dependent on the animal.

Describe the difference between a Thread and a Process?

Process Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads. Thread A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients.

What is a DependencyProperty?

Represents a property that can be set through methods such as styling, data binding, animation and inheritance.

Describe Bubble Sort

Runs through list swapping adjacent items until no swaps are needed. Worst Case Performance: O(n^2) Best Case Performance: O(n) Avg. Case Performance: O(n^2)

In reference to Object Oriented Design what does S.O.L.I.D. stand for?

S - Single-responsibility principle O - Open-closed principle L - Liskov substitution principle I - Interface segregation principle D - Dependency inversion principle

How do you Use Rank in SQL

SELECT *, MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC) FROM RSLTS ORDER BY MYRANK SELECT *, MYRANK = RANK() OVER (ORDER BY SCORE DESC) FROM RSLTS ORDER BY MYRANK

What does the keyword sealed do?

Set a class to where it cannot be inherited. Can set a method/property that overrides a virtual method/property and the there can be no override on it.

What is Open-Closed Principle?

Software entities, i.e. classes, modules, functions, and so forth, should be open for extension, but closed for modification

Describe Insertion Sort

Start with the first item, we say that is are sorted list, as one item is sorted, and to the right of that is unsorted. So take item 2 and add to the sorted section. Move to next and continue to the end. Worst Case Performance: O(n^2) Best Case Performance: O(n) Avg. Case Performance: O(n^2)

What is the difference between static and dynamic typing?

Static typing is when define a type for your variables and any operation is checked at compile time. Dynamic typing is when your type checking occurs at runtime and issues throw runtime errors. However you will get more versatile functions as they will only have to be written once for multiple types.

WPF: What are styles?

Styles are essentially a list of property setters. If applied to an element it sets all properties with the specified values. Defined: <Application.Resources> <Style x:Key="ButtonStyle" TargetType="Button"> <Setter Property="Control.Background" Value="Green" /> </Style> </Application.Resources> In Use: <Button Content="Button" Style="{StaticResource ButtonStyle}"/>

Regular Expression Call, Quantifiers, etc.

System.Text.RegularExpressions.Regex.IsMatch(".5", searchStr); \d - any decimal digit \D - any character other than a decimal \w - matches any word character \W - matches any non word character \s - any whitepace \d{3} - any three digits \d{3,} - at least three digits \d{3,5) - at least three, no more than 5 [ABL] - Any thing in that group, so A, B, or L [^ABL] - negation, not A, B, L [A-Z] - any capital letter \d* - 0 or more digits \d+ - 1 or more digits \d? - 0 or one digit . - matches any character except \n

How do you marshal a thread back to the UI thread.

That depends on what thread you're using to do the work. With a background worker, you do the work in dowork and you can set the event runworkercompleted to do code after the completion. BackgroundWorker _backgroundWorker = new BackgroundWorker();... // Set up the Background Worker Events _backgroundWorker.DoWork += _backgroundWorker_DoWork; backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted; With other tasks in WinForms you can use the Syncronization Context to marshall back to the UI thread. Meaning you can kick off any task, via a post. Another way if you're on the UI thread is to use TaskScheduler with ContinueWith: Task UITask= task.ContinueWith(() => { this.TextBlock1.Text = "Complete"; }, TaskScheduler.FromCurrentSynchronizationContext()); Application.Current.Dispatcher.BeginInvoke()

What is the difference between Action and Func?

The difference is simply weather you want the delegate to return a value (use Func) or not (use Action).

Clustered vs. NonClustered

The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.

Explain Garbage Collection generations?

There are three generations: 0, 1, 2, which apply to the managed objects. When a program starts the objects are all in Gen 0. When the GC comes after an undetermined amount of time, it will check these objects, the ones that are no longer needed the GC will reclaim its memory. Those that are still alive will be are moved to Gen 1. The same will be done from Gen 1 to Gen 2. Now the lower the generation the more often the GC actually does checks if the objects are still alive. Generations allow for enhancing GC performance.

Describe Selection Sort

This finds the minimum and sets that to the left. Worst Case Performance: O(n^2) Best Case Performance: O(n^2) Avg. Case Performance: O(n^2)

Explain a Hash Table

This is used when insertion, deletion and look up are important. A hash function is used to find out where in an array to store the value. Linear Probing is a way to handle collisions, where you just put value into next available slot. Separate Chaining is where collisions are handled by saving a list to the hash key

Different Thread Kickoffs and Waits

ThreadPool.QueueUserWorkItem(x => DoSomething()); var task = Task.Factory.StartNew(() => DoSomething); //()=> is an action Task.Factory.StartNew(DoSomething).ContinueWith(moreWork); //Same thing in 4.5 as Task.Run(DoSomething); Parallel.Invoke(ParallelOptions, Action[]); Parallel.ForEach(sourceCollection, x=>Process(x)); Task.WaitAll(task1, task2, task3); Task.WaitAny(task1, task2, task3); await Task.Delay(1000); Thread workerThread = new Thread(workerObject.DoWork); workerThread.Start(); while (!workerThread.IsAlive); workerObject.RequestStop(); workerThread.Join();

What gotchas have you experienced using MVVM?

ViewModel a place for code-behind References from ViewModel to View and if they should exist Reuse around ViewModels, or using several ViewModels

In MVVM what object do most ViewModels inherit from?

ViewModelBase

What is strong-typing versus weak-typing? Which is preferred? Why?

Weak typing is where a language allows you to treat blocks of memory defined as one type as another (casting). Strong typed is when the type is explicitly set and can not be used otherwise without doing a conversion. There is no preference.

What is the Facade Design Pattern?

When you need to connect to several subsystems, you can use the Facade Pattern, which will link up all the systems and calls you need to.

What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

Windows Service is a service application that must be installed onto a server before it can be ran. It isn't as simple to debug, some create a wrapper class and others install and start the service and then attach a debugger to it. The running of a server is not always that of the logged on user, in fact it should not have any code to interact with the user as this may cause the program to just stop.

Inheritance, with method hiding what are expected outputs?

public class A { public void DoSomething() { Console.WriteLine("I'm A"); } } public class B : A { public void DoSomething() { Console.WriteLine("I'm B"); } } //There will be a warning about hiding, if you add the keyword new it removes the warning A a = new B(); a.DoSomething(); //I'm A ((B)a).DoSomething(); //I'm B A a2 = new A(); ((B)a2).DoSomething(); //Error A can be cast to B

Quick way to remove an item from an Array object.

public static T[] RemoveAt<T>(this T[] source, int index) { T[] dest = new T[source.Length - 1]; if( index > 0 ) Array.Copy(source, 0, dest, 0, index); if( index < source.Length - 1 ) Array.Copy(source, index + 1, dest, index, source.Length - index - 1); return dest; }

Implicit vs. Explicit Cast. Syntax and what is the difference?

public static implicit operator Role(string roleName) { return new Role() {Name = roleName }; } //Can switch out implicit with explicit. The difference is that implicit will require no casting, something like Role role = "Name"; and explicit will require a cast like Role role = (Role)"Name";

Find Largest Prime

public static long FindLargestPrime(long num) { long counter = 2; //Project Euler Math trickery, will never be larger than sqrt of num // (the only thing I remember from Euler) while (counter * counter <= num) { if (num % counter == 0) { //Keep moving onto find the largest number // If this is an even number, divide by two, still even, divide by 2, once no longer even then move away from 2 // 12/2 = 6 /2 = 3 in other words, nothing under num /= counter; } else { counter++; } } return num; }

Property Changed structure

public string CompanyName { get {return this.companyNameValue;} set { if (value != this.companyNameValue) { this.companyNameValue = value; NotifyPropertyChanged("CompanyName"); } } }

How do you reverse a Linked List?

public void ReverseList() { Node prev = null; Node curr = _head; Node next; //Essentially we want to iterate through the list and point each node to the previous node while (curr != null) { next = curr.Next; curr.Next = prev; prev = curr; curr = next; } _head = prev; }

What is the fastest way to copy one array to another?

var intArray = new int[]{1,2,3,4,5,6,7,8,9}; int[] intArray2 = new int[intArray.Length]; Array.Copy(intArray, intArray2, intArray.Length); Or, arguably, Buffer.BlockCopy

Way to wait on a Thread Pool

var mre = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(_ => { DoSomeWork(); mre.Set(); }); mre.WaitOne();


Related study sets

Research C10 research study (done)

View Set

Corporate finance summer Ch. 8,13,14

View Set

NH Drivers Notes Chapter 13.1: Vehicle Malfunctions

View Set

LARE - Section 1 Practice Questions

View Set

Suicide Awareness and Prevention

View Set

Business Law II - Chapters 18 & 19

View Set

Astronomy Mid-term Part 2 (chapters 16, 6, 7)

View Set

Exam 2: Tracheostomy & Trach Care (NCLEX)

View Set

Practice Quiz Modifier Placement

View Set