Sunteți pe pagina 1din 30

Intrebari C# cruce ASP.

NET

Principiile POO:

- Abastractizare: posibilitatea ca un program s ignore unele aspect ale informaiei pe care o manipuleaz, adic posibilitatea de a se concentra asu nseamn identificarea similitudinilor ntre diferite entiti, situaii sau procese din lumea real , concentrarea ateniei asupra acest comune i ignorarea pentru nceput a detaliilor. identific trsturile caracteristice eseniale ale unui obiect, care l deosebesc de toate cele lalte feluri de obiecte. fiecare obiect n sistem are rolul unui actor abstract, care poate executa aciuni, i poate modifica i comunica starea i poate co alte obiecte din sistem fr a dezvlui cum au fost implementate acele facilitai. procesele, funciile sau metodele pot fi de asemenea abstracte

- Incapsulare ascunderea de informaii (data-hiding) obiectele nu pot schimba starea intern a altor obiecte n mod direct (ci doar prin metode puse la dispoziie de obiectul res pectiv); doar metodele proprii ale obiectului pot accesa starea acestuia. procesul de compartimentare a elementelor unei abstractizri n dou pri: structura i comportarea; ncapsularea separ comportarea (accesat prin interfa) de structur, definit prin implementare. fiecare tip de obiect expune o interfa pentru celelalte obiecte care specific modul cum acele obiecte pot interaciona cu el.

- Modularitate -este procesul de partiionare a unui program n componente individuale (module) ceea ce permite reducerea complexitii programulu unor granie bine stabilite i documentate n program. modularizarea const n partiionarea programului n module care pot fi compilate separat, dar care au conexiuni cu alte modu le ale modulele servesc ca i containere n care sunt declarate clasele i obiectele programului.

- Ierarhizare modalitatea de a ordona abstractizrile (tipurile abstracte de date). Ierarhiile pot s denote relaii de tip sau relaii de agregare. Relaiile de tip sunt definite prin motenirilentre clase, prin care o clas (clasa derivat) motenete structura sau comportarea definit n alt clas (clasa de baz ). Relaiile de agregare specific compunerea unui obiect din mai multe obiecte mai simple. Obs: n limbajele de programare procedural agregarea se realiza prin structuri de tip nregistrare Motenirea permite definirea i crearea unor clase specializate plecnd de la clase (generale) care sunt deja definite permite construirea unor clase noi, care pstreaz caracteristicile i comportarea, deci datele i funciile membru, de la una sau mai multe clase definite anterior, numite clase de baz, fiind posibil redefinirea sau adugarea unor date i funcii noi. o clas ce motenete una sau mai multe clase de baz se numete clasa derivat. posibilitatea refolosirii lucrurilor care funcioneaz organizeaz i faciliteaz polimorfismul i ncapsularea Anumite obiecte sunt similare dar n acelai timp diferite. Proprietatea de motenire: proprietatea claselor prin care o clas nou construit poate prelua datele i metodele clasei mai vechi. Clasa derivat se afl ntotdeauna pe un nivel imediat inferior celui corespunztor clasei de baz. Polimorfismul, suprancrcarea Mai multe funcii pot avea acelai nume n acelai domeniu de definiie, dac se pot diferenia prin numrul sau tipul argumentelor de apel. O funcie este polimorfic dac se poate executa cu acelai efect asupra unor valori de tipuri diferite (ex. operatorul & din C)

Un alt mecanism este suprancrcarea funciilor( function overloading). O funcie este suprancrcat dac execut operaii diferite n contexte diferite (ex. operatorul + din Java) Se poate aplica doar funciilor. Supradefinirea (overriding) ofer posibilitatea de a redefini metode pentru clasele derivate, metodele au acelai tip i aceeai parametri. Polimorfismul, suprancrcarea Dac n acelai domeniu sunt definite mai multe funcii cu acelai nume, la fiecare apel se selecteaz funcia corect prin compararea tipurilor argumentelor reale de apel cu tipurile argumentelor formale ale funciei. double abs(double); int abs(int); abs(1); // apeleaza abs(int) abs(1.0); // apeleaza abs(double) Nu este admis ca funciile s difere doar prin tipul returnat. Dou funcii declarate cu acelai nume se refer la aceeai funcie dac sunt n acelai domeniu i au numr i tipuri identi ce de argumente. Tipuri de mostenire in C#:
n C# exist doar motenire simpl, o ierarhie de clase n care fiecare clas derivat are o singur clas de baz. Exemplu. parallelogram dreptunghi romb patrat Clasa dreptunghi este o clas derivat (subclas) a clasei paralelogram, iar clasa paralelogram este o clas de baz (supraclas) a clasei dreptunghi. Astfel, o ierarhie de concepte conduce la o ierarhie ntre clasele care implementeaz conceptele ierarhice respective.

Apelezi dintr-o clasa derivata functionalitatea unei clase de baza? n POO cnd o clas derivat motenete de la o clas de baz, un obiect al clasei derivate poate fi considerat ca fiind (sau

convertit la) o instan a clasei de baz sau a unei clase derivate din aceasta. Dac exist funcii ale clasei de baz ce au fost redefin

derivat a fost convertit la (este referit ca fiind de) tipul clasei de baz. Cnd un obiect derivat este considerat ca fiind de tipul clasei de nedefinit. Distincia dintre virtual (dinamic) i static este fcut pentru a rezolva aceast problem. Dac funcia n cauz este etichetat drept "virtual" atunci funcia clasei derivate va fi apelat (dac ea exist). Dac e static, atunci va fi apelat funcia clasei de baz

Method overload? Overloading of methods permits a class, struct, or interface to declare multiple methods with the same name, provided their signatures are unique within that class, struct, or interface. Overloading of instance constructors permits a class or struct to declare multiple instance constructors, provided their signatures are unique within that class or struct. Overloading of indexers permits a class, struct, or interface to declare multiple indexers, provided their signatures are unique within that class, struct, or interface. Overloading of operators permits a class or struct to declare multiple operators with the same name, provided their signatures are unique within that class or struct. Modificatori de access:

public: accesibil din interiorul i din exteriorul clasei protected: accesibil numai din interiorul clasei i a claselor derivate internal: accesibil din interiorul din exteriorul clasei dar numai n cadrul assembly-ului (proiectului in VS) protected internal: accesibil numai din interiorul clasei i a claselor derivate n cadrul assembly-ului (proiectului in VS) private: accesibil numai din interiorul clasei

Interfata vs. Clasa abstracta


Ce este o interfata ? O interfata defineste un set de metode, proprietati, evenimente, indexatori. Acesti membri vor fi implementati de o clasa sau chiar de o structura. Pentru mai multe informatii despre interfete puteti consulta articolul Interfete in .Net. Ce este o clasa abstracta ? O clasa abstracta este o clasa care nu poate fi instantiata si este folosita pentru mostenire. O clasa care nu este abstracta si care deriveaza dintr-o clasa abstracta, trebuie sa includa implementarile tuturor membrilor abstracti. Vom crea o interfata si o clasa abstracta, apoi le vom implementa/mosteni. Observatii: Interfata contine doar signatura membrilor. Daca nu se specifica nici un modificator de acces pentru interfata, atunci cel implicit va fi internal. Daca se afla in interiorul unei clase, o interfata poate avea modificatorii de access private, protected, public, internal. O clasa poate implementa mai multe interfete. Clasa abstracta poate avea ca membri si campuri (field). O clasa poate mosteni o singura clasa abstracta. O clasa poate furniza atat membri abstracti cat si membri cu implementare concreta. Daca adaugam un nou membru la o clasa abstracta ii putem adauga o implementare implicita si nu vom avea probleme cu codul existent. Concluzii: O interfata nu contine cod pentru implementare, ea contine doar signaturile. O clasa abstracta poate contine codul complet sau partial, care poate fi rescris. O interfata nu poate contine ca membri: constante, constructori, destructori, campuri, membri statici sau alte interfete. Intr-o clasa abstracta se pot defini campuri, constante, metode, proprietati.

Din punct de vedere al vitezei de executie, o interfata este mai lenta decat o clasa abstracta.

Clasa (heap) vs. Struct(stack) :


The stack is a data structure in memory used for storing items in a last-in, first-out manner (LIFO). The stack contains both local variables and the call stack. In C#, value types are stored on the stack. Local variables Local variables are variables that are declared inside a method. They can be of either value type or reference type. Value type variables are stored directly on the stack. A reference type variable is actually a numerical address pointing to a location on the heap where the object is stored. Call stack Every C# application begins with a Main method. In turn, it calls other methods which call still other methods. When a method is called, it is added to the top of the stack. And, when a method returns to its caller, it is removed from the stack. Execution continues with the calling method. Scope Scope defines the lifetime of a variable. The block of code in which a variable is declared is its scope. When the block in which a variable is declared begins execution, the variable's lifetime begins when it is pushed onto the stack as part of the call stack. When execution leaves the block in which the variable was declared, the call stack and variables are popped off the stack. The variable's lifetime has ended. The Heap The heap or managed heap is a data structure in memory where all objectsreference typesare stored. When an object is instantiated, the object is stored on the heap as a block of data containing its data members. Then, the memory address of the block is stored in a reference variable. Future references to the object are through the reference variable. In C#, the new operator is used to instantiate a class and return the reference to the object on the heap. Summary The following table summarizes the differences between the Heap and the Stack:

Memory Contents

Item Order

Item Lifetime

Item Removal

Timing

Stack

value types, stack frames sequential (LIFO) scope

pop

deterministic

Heap

objects

random

reference count Garbage Collection nondeterministic

Boxing / Unboxing?
Boxing Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Consider the following declaration of a value-type variable: int i = 123;

The following statement implicitly applies the boxing operation on the variable i: // Boxing copies the value of i into object o. object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable for example:(Consider follwing C# code) class TestBoxing { static void Main() { int i = 123; // Boxing copies the value of i into object o. object o = i; // Change the value of i. i = 456; // The change in i does not effect the value stored in o. System.Console.WriteLine("The value-type value = {0}", i); System.Console.WriteLine("The object-type value = {0}", o); } } /* Output: The value-type value = 456 The object-type value = 123 */ Unboxing Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:

Checking the object instance to make sure that it is a boxed value of the given value type. Copying the value from the instance into the value-type variable. int i = 123; // a value type object o = i; // boxing int j = (int)o; // unboxing

String vs. StringBuilder? string is immutable whereas stringbuilder is mutable, for ex: string s="abc";

s="lmn"; s="xyz"; s string always create new object of string type in memory. but when you use string builder class, it will update string at one place in memory doesnt create new space in memory. Poate fi DateTimes null?
Nullable<DateTime> _myDateTime; will work, you should be able to set it to null Check for nulls: if (object.myDateTime != null) or if (object.myDateTime.HasValue)

Care este dinferenta dintre un dll si un exe file?


EXE: 1. 2. 3. It's a executable file When loading an executable, no export is called, but only the module entry point. When a system launches new executable, a new process is created

4. The entry thread is called in context of main thread of that process. DLL: 1. 2. 3. It's a Dynamic Link Library There are multiple exported symbols. The system loads a DLL into the context of an existing process.

Care este scopul using () {} block ? ce este IDisposable? File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

Ce este o exceptie? Cum putem prinde o exceptie?


try { ... } catch () { ... } /* You can even omit the () here */

try { ... } catch (Exception e) { ... } are similar in that both will catch every exception thrown inside the try block (and, unless you are simply using this to log the exceptions, should be try { ... } catch () { /* ... */ throw; } try { ... } catch (Exception e) { /* ... */ throw; } try { ... } catch (Exception e) { /* ... */ throw e; } The first and second try-catch blocks are EXACTLY the same thing, they simply rethrow the current exception, and that exception will keep its "source" and the stack trace. The third try-catch block is different. When it throws the exception, it will change the source and the stack trace, so that it will appear that the exception has been thrown from this method, from that very line throw e on the method containing that try-catch block. Which one should you use? It really depends on each case. Let's say you have a Person class with a .Save() method that will persist it into a database. Let's say that your application executes the Person. Save() method somewhere. If your DB refuses to save the Person, then .Save() will throw an exception. Should you use throw or throw e in this case? Well, it depends. What I prefer is doing: try { /* ... */ person.Save(); } catch(DBException e) { throw new InvalidPersonException( "The person has an invalid state and could not be saved!", e); } This should put the DBException as the "Inner Exception" of the newer exception being throw. So when you inspect this InvalidPersonException,

the stack trace will contain info back to the Save method (that might be sufficient for you to solve the problem), but you still have access to the original exception should yuo need it. As a final remark, when you are expecting an exception, you should really catch that one specific exception, and not a general Exception, ie, if you are expecting an InvalidPersonException you should prefer: try { ... } catch (InvalidPersonException e) { ... } to try { ... } catch (Exception e) { ... } Good luck!

Ce este un constructor static? Ce este Garbage Collector? Static constructors have the following properties: A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor cannot be called directly. The user has no control on when the static constructor is executed in the program. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running. In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits: Enables you to develop your application without having to free memory. Allocates objects on the managed heap efficiently. Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field. Provides memory safety by making sure that an object cannot use the content of another object.

Care este diferenta intre Dispose() si Finalize()?


Din ciclul chestiunea zilei, Finalize si Dispose, in c#. Ambele metode sunt executate cand un obiect este distrus. In mod normal Garbage Collector (zis in continuare GC) elibereaza memoria curatand obiectele aflate acolo sprea care nu exista nici o referinta. Cu alte cuvinte, daca avem asa: Person p = new Person("gigel"); p = null; vine GC si curata ceea ce am instantiat in p, fara a necesita ca eu, programator, sa ma preocup de curatenie. Frumos, nu? As vrea si

in bucatarie sa existe un GC care sa faca curatenie dupa ce eu gatesc.Asa as gati mai des si mai cu chef! Oricum, pana ce o sa am versiunea aia de bucatarie echipata cu GC sa ma inteorc la . Net.

Ce e cu Dispose? Exista o interfata, IDisposable, care contine o metoda Dispose(); Cine implementeaza aceasta interfata in clasa lui, si-a cumparat un loc la procesul de deratizare. In momentul in care un obiect este curatat din memorie, GC executa, daca poate, Dispose(). Aceasta metoda poate fi executata si de user. Ce e cu Finalize? Aceasta este versiunea de destructor in .Net. Cum se scrie aceasta? Simplu:

public class Person { public Person() { /* constructor code goes here */ } ~Person() { /* destructor */ } }
ceea ce compilerul traduce in:

protected override void Finalize() { try { // do work here } finally { base.Finalize(); } }


Atat in Finalize cat si in Dispose, in mod normal, ar trebui eliberate resursele unmanaged folosite de obiect. Diferenta dintre cele doua este, simplu spus, ca Dispose poate fi executat de user (este ok sa scrii instance.Dispose(), insa Finalise este executat numai de GC. Nu este legal sa fie executat la dorinta programatorului. uitasem sa spun: GC vine cand vrea el, in .Net nu este controlabil momentul in care GC va face munca de curatenie. E la fel ca programatorul care vine la munca intre 8 si 12, in functie de cat de mult a fumat cu o zi inainte.

2. Ce inseamana lock?(Cu ce este echivalent lock?) Obtine excluderea mutuala asupra unui obiect pentru executarea unui bloc de instructiuni. Are forma: lock (x) instructiune X trebuie sa e de tip referinta (daca este de tip valoare, nu se face boxing) 3. Care este diferenta fundamentala dintre SQLAdapter si SqlDataReader?

qlDataReader:

Holds the connection open until you are finished (don't forget to close it!). Can typically only be iterated over once Is not as useful for updating back to the database

On the other hand, it:


SqlDataAdapter/DataSet

Only has one record in memory at a time rather than an entire result set (this can be huge) Is about as fast as it you can get for that one iteration Allows you start processing results sooner

Lets you close the connection as soon it's done loading data, and may even close it for you automatically All of the results are available in memory You can iterate over it as many times as you need, or even look up a specific record by index Has some built-in faculties for updating back to the database At the cost of: Much higher memory use You wait until all the data is loaded before using any of it So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid.

4. Poate avea un thread parametri? nu 5. Ce reprezinta remoting? n .NET Framework remoting-ul reprezint modalitatea prin care procesele pot interaciona dincolo de un anumit context. Acest context poate fi sistemul de operare pentru procesele de pe acelai calculator sau reeaua de calculatoare pentru procesele aflate pe maini diferite. .NET extinde acest conceptul de context pan la nivelul aplicaiei. NET Remoting recunoate dou tipuri de clase a cror instane sunt accesate n mod diferit: - prin valoare sau marshal by value (MBV); - prin referin sau marshal by reference (MBR). 6. Ce reprezinta un WebService?
Este un lucru foarte normal ca dou programe (procese) sa comunice intre ele pe acceasi masina, folosind fisiere, IPC-uri, pipe-uri, cozi de mesaje, memorie partajata etc. Acest lucru se poate generaliza si la nivel de mai multe masini, adica aceleasi doua programe pot exista pe masini diferite, unul server iar celalalt client, metoda de comunica fiind socketii. Un exemplu foarte la indemana este un client (un browser Firefox) si un server ruland Apache, comunicand la nivel http , dar de multe ori se doreste ca serverul sa faca lucruri ceva mai complicate decat sa trimita clientului o pagina html, cum ar fi sa execute niste calcule foarte complexe si sa transmita rezultatul clientului. Acest lucru s-ar putea face in nenumarate feluri. O modalitate ar fi sa copii (scp) un script care face calculele, sa te conectezi apoi pe server si sa executi scriptul (ssh), apoi sa preiei rezultatele, dar aceasta metoda este

destul de obositoare, mai ales cand trebuie sa repeti operatiunea. Web Services vin in ajutorul nostru, facand toate aceste lucruri intr-un mod unitar, generic si standardizat, toate pe baza paradigmei client-server. Cum functioneaza un web service Diagrama :

+--------------------------------------+ | | | ^ | (2) | | | | | v +-----------+ | service | requestor | +-----------+ (3) (the client finds the service they want) WSDL web service registry (aka service broker) (UDDI) ^ | (1) | | | | | | +-----------+ service | | provider | |<---SOAP--->| (the web service provider publishes the web service) WSDL | | |

+--------------------------------------+

+-----------+

7. Ce este ViewState? Care sunt dezavantajele de la ViewState?


If the search object isn't huge in size, then go with using a ViewState. A ViewState is perfect if you only want the object to live for the current page's lifecycle. A session object is also fine to use, but obviously once the search object is in there, it will be around for longer the page's lifecycle.

8. Ce reprezinta Reflection?
Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies , modules and types. A program reflects on itself by extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior. Reflection is similar to C++ RTTI (Runtime Type Information), but much broader in scope and capability. By using Reflection in C#, one is able to find

out details of an object, method, and create objects and invoke methods at runtime. The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. When writing a C# code that uses reflection, the coder can use the typeof operator to get the object's type or use the GetType() method to get the type of the current instance Example 1 Collapse | Copy Code using System; using System.Reflection; public class MyClass { public virtual int AddNumb(int numb1,int numb2) { int result = numb1 + numb2; return result; } } class MyMainClass { public static int Main() { Console.WriteLine ("\nReflection.MethodInfo"); // Create MyClass object MyClass myClassObj = new MyClass(); // Get the Type information. Type myTypeObj = myClassObj.GetType(); // Get Method Information. MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb"); object[] mParam = new object[] {5, 10}; // Get and display the Invoke method. Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " + myMethodInfo.Invoke(myClassObj, mParam) + "\n"); return 0; } } Firstly, the code snippet below will get the type information: Collapse | Copy Code Type myTypeObj = Type.GetType("MyClass"); And myTypeObj will now have the required information about MyClass. Therefore we can now check if the class is An abstract class or a regular class by using either of these statements: Collapse | Copy Code myTypeObj.IsAbstract

or: Collapse | Copy Code myTypeObj.IsClass The code snippet below will get the method's information. And the method that we are interested in this case is AddNumb: Collapse | Copy Code Methodinfo myMethodInfo = myTypeObj.GetMethod("AddNumb"); The following code snippet will invoke the AddNumb method: Collapse | Copy Code myMethodInfo.Invoke(myClassObj, mParam); //Example2: In this example, we will use the typeof keyword to obtain the // System.Type object for a type. Public class MyClass2 { int answer; public MyClass2() { answer = 0; } public int AddNumb(intnumb1, intnumb2) { answer = numb1 + numb2; return answer; } } The code snippet below gets the System.Type object for the MyClass2 type. Collapse | Copy Code Type type1 = typeof(MyClass2); So we will now be able to create an instance of the type1 object by passing the type1 object to the Activator.CreateInstance(type1) method. Collapse | Copy Code

object obj = Activator.CreateInstance(type1); Then we can now invoke the AddNumb method of the MyClass2 class by first creating an array of objects for the arguments that we would be passing to the AddNumb(int, int) method. Collapse | Copy Code object[] mParam =newobject[] {5, 10}; Finally, we would invoke the AddNumb(int, int) method by passing the method name AddNumb toSystem.Type.InvokeMember() with the appropriate arguments. Collapse | Copy Code int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,null, obj, mParam); //Here is the complete code: using System; using System.Reflection; namespace Reflection { class Class1 { public int AddNumb(int numb1, int numb2) { int ans = numb1 + numb2; return ans; } [STAThread] static void Main(string[] args) { Type type1 = typeof(Class1); //Create an instance of the type object obj = Activator.CreateInstance(type1); object[] mParam = new object[] {5, 10}; //invoke AddMethod, passing in two parameters int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod, null, obj, mParam); Console.Write("Result: {0} \n", res); } }

9. Care este diferenta intre class si struct?

Nu este nici o diferenta intre clasele definite utilizand cuvantele cheie struct si class, exceptand accesul implicit la membri si la clasele de baza.

pentru struct accesul implicit este public; pentru class accesul implicit este private.

Diferena principal ntre specificatorii class, struct i union este urmtoarea: pentru o clas declarat folosind specificatorul class, datele membre sunt considerate implicit de tip private, pn la prima folosire a unuia din specificatorii de acces public sau protected. Pentru o clas declarat folosind specificatorul struct sau union, datele membre sunt implicit de tip public, pn la prima folosire a unuia din specificatorii private sau protected. Specificatorul protected se folosete doar dac este folosit motenirea.

11. Ce inseamna transmitere prin referitna si valoare?


Tipurile valoare In articolul Tipuri valoare am expus clasificarea acestora. Conform documentatiei SDK .Net, tipul valoare poate fi reprezentat de o structura (struct) sau de o enumerare (enum). De exemplu, structuri ca System.Int32 sau System.Boolean,Sytem.DayOfWeek sunt tipuri valoare. Este importantat de mentionat ca toate structurile si enumerarile deriva din tipul abstract System.ValueType care la randul lui deriva din clasa de baza System.Object. Un tip valoare nu poate fi folosit ca baza pentru crearea unui alt tip valoare, toate tipurile valoare fiind sealed. Prin urmare, programatorul nu isi poate crea un tip valoare pornind de la un tip de baza ca Boolean sau Char. De aceea, un tip valoare nu poate avea membri abstracti. Urmatorul cod va genera eroare la compilare: The modifier abstract is not valid for this item. In schimb, un tip valoare poate implementa una sau mai multe interfete. Tipul valoare nu este supus GC, el se termina o data cu metoda, nu accepta finalizer si nu este referentiat de un pointer. Tipurile referinta Despre tipurile referinta s-a discutat in articolul Tipurile referinta. Ele sunt reprezentate de clase, interfete, delegati, siruri de caractere si tipul object (tipul de baza). Tipurile referinta stocheaza in stack pointer-ul catre date, date care sunt stocate in heap. Memoria alocata tipurilor referinta este in heap, ceea ce poate conduce la o declansare a GC. Asignarea unei variabile de tip referinta catre o alta instanta de tip de tip referinta va crea o copie care va referi aceeasi locatie din heap. Tip valoarea sau tip referinta? In procesul de proiectare al propriilor tipuri de date, programatorul trebuie sa aleaga cu atentie intre cele doua tipuri.stfel, cateva situatii ce recomanda tipurile valoare pentru crearea unui tip nou: o mai buna performanta intrucat nu sunt alocate in heap tipul este simplu, immutable (sa nu aiba membri ce pot modifica campurile) tipul nu este tip de baza si nu mosteneste un alt tip

marimea instantei este relativ mica, mai mica de 16 biti marimea instantei este mare, dar tipul nu este este folosit in transmiterea parametrilor sau ca tip returnat (transmiterea parametrilor se face implicit prin valoare, ceea ce inseamna copierea valorilor campurilor si afectarea performantei) Aceste doua tipuri de date prezentate de C# creeaza un paradox: in bibliotecile puse la dispozitie de FCL tipurile de referinta sunt cele mai intalnite, dar tipurile valoare sunt cele mai folosite de programatori. Chiar daca pentru dezvoltatorii de unmanaged C/C++ aceasta clasificare poate parea ciudata, ea contribuie la performanta aplicatiei. Sa ne imaginam cum ar fi fost daca pentru fiecare int cerut de programator ar fi avut loc intregul proces de alocare in memoria heap.

14. Ce inseamna cuvantul cheie virtual? The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it: public virtual double Area() { return x * y; } When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. By default, methods are non-virtual. You cannot override a non-virtual method. You cannot use the virtual modifier with the static, abstract, private, or override modifiers. The following example shows a virtual property:

15. Care este diferenta intre clasa abstracta si interfata?


Clase abstracte

Dorim sa stabilim interfata comuna pentru a putea crea functionalitate diferita pentru fiecare subtip si pentru a sti ce anume au clasele derivate in com O clasa cu caracteristicile enumerate mai sus se numeste abstracta. Cream o clasa abstracta atunci cand dorim sa:

manipulam un set de clase printr-o interfata comuna reutilizam o serie metode si membrii din aceasta clasa in clasele derivate.

Metodele suprascrise in clasele derivate vor fi apelate folosind dynamic binding (late binding). Acesta este un mecanism prin care compilatorul, in m la baza polimorfismului.

metode in avans, lasa la latitudinea JVM-ului (masinii virtuale) alegerea implementarii potrivite, in functie de tipul real al obiectului. Acesta legare a im

Nu exista instante ale unei clase abstracte, aceasta exprimand doar un punct de pornire pentru definirea unor instrumente reale. De aceea, crearea compilatorul Java semnaland eroare in acest caz. Metode abstracte

Pentru a exprima faptul ca o metoda este abstracta (adica se declara doar interfata ei, nu si implementarea), Java foloseste cuvantul cheie abstrac abstract void f();

O clasa care contine metode abstracte este numita clasa abstracta. Daca o clasa are una sau mai multe metode abstracte atunci ea trebuie sa co Exemplu: abstract class Instrument { ... }

Deoarece o clasa abstracta este incompleta (exista metode care nu sunt definite), crearea unui obiect de tipul clasei este impiedicata de compilator. Clase abstracte in contextul mostenirii

O clasa care mosteneste o clasa abstracta este ea insasi abstracta daca nu implementeaza toate metodele abstracte ale clasei de baza. Putem def asa. O clasa care poate fi instantiata (nu este abstracta) si care mosteneste o clasa abstracta trebuie sa implementeze (defineasca) toate metodele care ii sunt "parinti").

Este posibil sa declaram o clasa abstracta fara ca ea sa aiba metode abstracte. Acest lucru este folositor cand declaram o clasa pentru care nu d tipul acelei clase, chiar daca definita ei este completa). Iata cum putem sa modificam exemplul instrument cu metode abstracte:

Interfete

Interfetele duc conceptul abstract un pas mai departe. Se poate considera ca o interfata este o clasa abstracta pura: permite programatorului sa s de argumente, valori intoarse, dar fara nicio implementare. O interfata poate contine campuri dar acestea sunt in mod implicit static si final.

Interfata este folosita pentru a descrie un protocol intre clase: o clasa care implementeaza o interfata va implementa metodele definite in interfata. A metode pot fi apelate pentru acea interfata.

Pentru a crea o interfata folosim cuvantul cheie interface in loc de class. La fel ca in cazul claselor, interfata poate fi declarata public doar dac Daca o interfata nu este declarata public atunci specifcatorul ei de acces este package-private.

Pentru a defini o clasa care este conforma cu o interfata anume folosim cuvantul cheie implements. Aceasta relatie este asemanatoare cu mosten doar "interfata". Pentru a defini o interfata care mosteneste alta interfata folosim cuvantul cheie extends. Dupa ce o interfata a fost implementata, acea implementare devine o clasa obisnuita care poate fi extinsa prin mostenire. Iata exemplul dat mai sus, modificat pentru a folosi interfete:

Codul arata astfel: interface Instrument { // Compile-time constant: int i = 5; // static & final // Cannot have method definitions: void play(); // Automatically public String what(); void adjust(); }

class Suflat implements Instrument { public void play() { System.out.println("Suflat.play()"); } public String what() { return "Suflat"; } public void adjust() {} } class Trompeta extends Suflat { public void play() { System.out.println("Trompeta.play()"); } public void adjust() { System.out.println("Trompeta.adjust()"); } }

Implicit, specificatorul de acces pentru membrii unei interfete este public. Atunci cand implementam o interfata trebuie sa specificam ca functiile su

explicit astfel. Acest lucru este necesar deoarece specificatorul de acces implicit in clase este package-private, care este mai restrictiv decat pu Extinderea interfetelor Se pot adauga cu usurinta metode noi unei interfete prin extinderea ei intr-o alta interfata: Exemplu: interface Monster { void menace(); } interface DangerousMonster extends Monster { void destroy(); } Deoarece campurile unei interfete sunt automat static si final, interfetele sunt un mod convenabil de a crea grupuri de constante, asemanatoare cu enum-urile din C , C++. Initializarea campurilor in interfete In interfete nu pot exista blank finals (campuri final neinitializate) insa pot fi initializate cu valori neconstante. Campurile fiind statice, ele vor fi initializate prima oara cand clasa este initializata

17. Ce inseamna sealed? When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B. class A {} sealed class B : A {}

You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

19. Ce inseamana dispose? The pattern for disposing an object, referred to as a dispose pattern, imposes order on the lifetime of an object. The dispose pattern is used only for objects that access unmanaged resources. This is because the garbage collector is very efficient at reclaiming unused managed objects. A type's Dispose method should release all the resources that it owns. It should also release all resources owned by its base types by calling its parent type's Dispose method. The parent type's Dispose method should release all resources that it owns and in turn call its parent type's Dispose method, propagating this pattern through the hierarchy of base types. A base class with subclasses that should be disposable must implement IDisposable as follows: It should provide one public, non-virtual Dispose() method and a protected virtual Dispose(Boolean disposing) method. The Dispose() method must call Dispose(true) and should call the GC.SuppressFinalize method to suppress finalization for better performance. The base type should not include any finalizers.

20. Ce inseamna overriden? The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. 21. Care este obiectul de baza in C#? Care sunt metodele pe care le are acest obiect? Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
Equals(Object) Determines whether the specified object is equal to the current object.

Equals(Object, Object)

Determines whether the specified object instances are considered equal.

Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaime

GetHashCode

Serves as the default hash function.

GetType

Gets the Type of the current instance.

MemberwiseClone

Creates a shallow copy of the current Object.

ReferenceEquals

Determines whether the specified Object instances are the same instance.

ToString

Returns a string that represents the current object.

22. Ce este un Mutex? Dar un Monitor?


A Monitor is managed, and more lightweight - but is restricted to your AppDomain. A Mutex can be named, and can span processes (allowing some simple IPC scenarios between applications), and can be used in code that wants a wait-handle). For most simple scenarios, Monitor (via lock) is fine.

25. Cum pot elibera memorie? Folosing GC- si apeland Finalize sau Dispose() 26. Ce caracterizeaza o exceptie? Unde se arunca exceptia?
O exceptie este un eveniment ce se produce n timpul executiei unui program si care provoaca ntreruperea cursului normal al executiei. Crearea unui obiect de tip exceptie se numeste aruncarea unei exceptii ("throwing an exception"). In momentul n care o metoda genereaza o exceptie (arunca o exceptie) sistemul de executie este responsabil cu gasirea unei secvente de cod dintr-o metoda care sa trateze acea exceptie. Cautarea se face recursiv, ncepnd cu metoda care a generat exceptia si mergnd napoi pe linia apelurilor catre acea metoda. Secventa de cod dintr-o metoda care trateaza o anumita exceptie se numeste analizor de exceptie ("exception handler") iar interceptarea si tratarea exceptie se numeste prinderea exceptiei ("catch the exception"). Cu alte cuvinte la aparitia unei erori este "aruncata" o exceptie iar cineva trebuie sa o "prinda" pentru a o trata. Daca sistemul nu gaseste nici un analizor pentru o anumita exceptie atunci programul Java se opreste cu un mesaj de eroare (n cazul exemplului de mai sus mesajul "Aici nu se mai ajunge..." nu va fi tiparit).

30. Ce reprezinta supraincarcarea operatorilor? Suprancrcarea operatorilor Suprancrcarea operatorilor n C# se face numai prin metode statice membre n clase. Exist trei forme de suprancrcare: Operatori de conversie explicii (conversia trebuie fcut implicit printr -un cast) sau implicii (conversia poate fi fcut automat de ctre compilator): public static implicit operator tip_returnat (NumeClasa param); sau public static explicit operator tip_returnat (NumeClasa param); Operatori unari pentru suprancrcarea operatorilor +, -, ~, !, ++ i --: public static tip_returnat operator operatorul (NumeClasa param); Operatori binari pentru suprancrcarea operatorilor +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >= i <=: public static tip_returnat operator operatorul (NumeClasa param, tip operand2); Se observ c nu poate fi suprancrcat operatorul de atribuire. Unii operatori trebuie suprancrcai numai n pereche (== i !=, < i >, <= i >=). n cazul n care se

suprancarc unul din operatorii binari +, -, /, *, |, &, ^, >>, <<, compilatorul va genera automat i suprancrcri pentru operatorii derivai +=, -=, /=, *=, |=, &=, ^=, >>=, <<=.

31. Ce inseamna delegat? Ce este un delegate ? In esenta, un delegate este un obiect type-safe ce puncteaza la o metoda (sau posibil o lista de metode) din cadrul aplicatiei, metoda ce poate fi invocata mai tarziu. Un obiect delegate mentine urmatoarele informatii : Adresa metodei pe care se face apel; Argumentele (daca exista) acestei metode; Valoarea de retur (daca exista) a acestei metode. Dupa ce am creat delegate si am furnizat informatiile necesare, acesta poate invoca in mod dinamic metoda (metodele) la care puncteaza. Metodele pot fi apelate sincron sau asincron. Definirea unui delagate in C#, exemplu: public delegate void Feedback( Object value, Int32 item, Int32 numItems);

32. Ce inseamna delegat multicast? System.MulticastDelegate Se refera la un alt obiect delegate. In mod normal are valoarea null. Este folosit pentru a crea o lista inlantuita de obiecte MulticastDelegate 33. Ce inseamna o functie asincrona? 34. ce Inseamna cuvantul cheie static? Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

35. Ce este un constructor static? A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is call any static members are referenced. Static constructors have the following properties: A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor cannot be called directly. The user has no control on when the static constructor is executed in the program. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

36. Ce inseamana cuvantul cheie ref? Dar out? The out contextual keyword is used in two contexts: As a parameter modifier in parameter lists In generic type parameter declarations in interfaces and delegates The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method. The value of a reference parameter is always the same as the value of the underlying argument variable. 37. Care e diferenta dintre (string) obj si obj as string?

38. Ce reprezinta un atribut? Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection. For more information, see Reflection (C# and Visual Basic). Attributes have the following properties: Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required. For more information, see, Creating Cust You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties. Attributes can accept arguments in the same way as methods and properties. Your program can examine its own metadata or the metadata in other programs by using reflection. For more information, see Accessing Attributes by Using Reflection (C# and Visual Basic).

40. ce contine manifestul unui assembly? Represents an assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application. 41. ce reprezinta GAC?

Global Assembly Cache :-- Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework. We can register the assembly to global assembly cache by using gacutil command. We can Navigate to the GAC directory, C:\winnt\Assembly in explore. In the tools menu select the cache properties; in the windows displayed you can set the memory limit in MB used by the GAC
42. Ce reprezinta un indexer? ndexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters. In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values. The Program class creates an instance of this class for storing strings.

43. Cum se poate porni un proces? Process.start(); 44. Ce reprezinta un timer? 45. Cum se poate tipari o imagine direct din cod in ASP.NET pe o pagina web?

46. Ce reprezinta serializarea? 47. Cum creez o clasa serilizabila? Exemplu de clasa neserializabila! 48. Ce inseamana Enumerator? 49. Ce inseamna Enumerable?

Design Patterns.

1. Ce este un singleton? 2. Ce este un adapter? 3. Ce este un enumerator?

MS SQL 2000

1. Ce reprezinta o tranzactie?
O tranzactie reprezinta una sau mai multe instructiuni SQL care compun o singura unitate logica de lucru. Tranzactia ncepe cu prima instructiune SQL executata si se ncheie n momentul n care efectele tranzactiei sunt salvate sau sunt derulate napoi.

2. De cate tipuri sunt joinurile? Comentarii! An SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by using values common to each. ANSI-standard SQL specifies five

types of JOIN: INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER and CROSS. As a special case, a table (base table, view, or joine

A programmer writes a JOIN statement to identify the records for joining. If the evaluated predicate is true, the combined record is the temporary table.

3. Ce reprezinta un cursor? In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator. Cursors are used by database programmers to process individual rows returned by database system queries. Cursors enable manipulation of whole result sets at once. In this scenario, a cursor enables the rows in a result set to be processed sequentially. In SQL procedures, a cursor makes it possible to define a result set (a set of data rows) and perform complex logic on a row by row basis. By using the same mechanics, a SQL procedure can also define a result set and return it directly to the caller of the SQL procedure or to a client application.

A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only reference one row at a time, but can move to other rows of the result set as needed. 4. Care sunt cuvintele cheie pentru SELECT? 5. Care este diferenta intre HAVING si WHERE? 6. Ce inseamna functii agregat? 7. Ce reprezinta trigerele? 8. Care e diferenta intre proceduri stocate si functii? 9. Ce reprezinta un index, dar un index clustered? 10. Ce reprezinta un connection pool?

Intrebari generale 1. ce este o sectiune critica? Prin resurs critic este indicat o resurs care poate fi ocupat i folosit la un moment dat numai de ctre un singur proces. Prin seciune critic se indic o poriune de cod care nu poate fi executat la un moment dat dect de un singur task i care seciune, odat iniiat, execuia ei trebuie s fie terminat fr a fi ntrerupt de un alt task. OBS - Seciunile critice trebuie s fie, de regul, ct mai scurte posibil deoarece toate celelalte task-uri sunt ntrziate pn la terminarea execuiei unei asemenea seciuni critice. -Problema seciunii critice prezint un interes deosebit, att din punct de vedere teoretic, ct i din punct de vedere practic. Majoritatea "subtilitilor" programrii concurente se leag, ntr-un fel sau altul de ea. 2. Care e diferenta intre thread si proces?

3. Ce reprezinta un semafor? Conceptul de semafor a fost introdus de Dijkstra, pentru a facilita sincronizarea proceselor, prin protejarea seciunilor critice i asigurarea accesului exclusiv la resursele pe care procesele le acceseaz. Seciunile critice sunt secvene de instruciuni care pot genera race condition i a cror execuie de ctre mai multe procese trebuie controlat. Formal, un semafor se poate defini ca o pereche (v(s),c(s)) unde: -v(s) este valorea semaforului- un nr. ntreg a crui valoare poate varia pe durata execuiei diferitelor procese. Iniializabil cu 1 sau 0 (TRUE sau FAlSE); -c(s) o coad de ateptare la semafor - conine referine la procesele care ateapt la semaforul s. Iniial coada este vid, iar disciplina cozii depinde de sistemul de operare (LIFO, FIFO, prioriti, etc.). Fiecrei seciuni critice trebuie s i se aloce un semafor. n UNIX noiunea de semafor a fost generalizat prin posibilitatea de a executa mai multe operaii asupra unuui semafor inclusiv incrementare decrementare cu valori diferite de 1. Din punct de vedere conceptual, o variabil mutex este echivalent cu un semafor s, care poate lua dou valori: 1 pentru starea neblocat i 0 pentr starea blocat. (Un astfel de semafor se va numi semafor binar). Operaiile asupra unei variabile mutex m se definesc, cu ajutorul semafoarelor, astfel: Iniializare: se definete un semafor m astfel nct v0(m) = 1. Blocare: (dup o eventual deblocare de ctre alt thread): P(m). Deblocare: V(m). Distrugere: distrugerea semaforului m.

Un semafor general este o variabil ntreag, ce poate lua doar valori pozitive i singurele operaii ce se pot efectua asupra lui sunt operaiile primitive P i V. Dac semaforul are valoarea zero, un program (task) ce ncearc s efectueze o operaie P asupra acestuia va fi suspendat (blocat) i va atepta pn cnd un alt program va efectua asupra aceluiai semafor o operaie V

50. Ce inseamna AppDomain? Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited. NET introduce o alta notiune, cea de application domains (AppDomain). AppDomain constituie un mediu izolat unde se executa aplicatia. AppDomain poate fi asimilat ca fiind un subproces ce ruleaza in cadrul unui proces. Un process poate contine mai multe AppDomain-uri, iar intrun AppDomain se poate incarca un assembly pentru executie. 51. Ce reprezinta Global.asax? Fiierul Global.asax: Conine funciile de tratare a evenimentelor globale ale aplicaiei (lansarea aplicaiei, cereri, etc.) 52. Ce reprezinta CLR?

CLR este de departe cea mai importanta componenta a lui .NET Framework. Este responsabila cu managementul si executia codului scris n limbaje .NET, aflat n format CIL; este foarte similar cu Java Virtual Machine. CLR instantiaza obiectele, face verificari de securitate, depune obiectelen memorie, disponibilizeaza memoria prin garbage collection. In urma compilarii unei aplicatii poate rezulta un fi sier cu extensia exe, dar care nu este un executabil portabil Windows, ci un executabil portabil .NET (.NET PE). Acest cod nu este deci un executabil nativ, ci se va rula de catre CLR, ntocmai cum un fisier class este rulat n cadrul JVM.
53. Exemple de limbaje sub platforma .NET. C#, Visual Basic .net, J#, IronPython 54. Ce este JIT?

CLR foloseste tehnologia compilarii JIT - o implementare de masina virtuala, n care o metoda sau o functie, n momentul n care este apelata pentru prima oara, este tradusa n cod masina. Codul translatat este depus ntr-un cache, evitand-se astfel recompilarea ulterioara. Exista 3 tipuri de compilatoare JIT: 1. Normal JIT - a se vedea descrierea de mai sus. 2. Pre-JIT - compileaza ntregul cod n cod nativ singura data. In mod normal este folosit la instalari. 3. Econo-JIT - se foloseste pe dispozitive cu resurse limitate. Compileaza codul CIL bit cu bit, eliberand resursele folosite de codul nativ ce este stocat n cache. In esenta, activitatea unui compilator JIT este destinata a mbunatati performanta executiei, ca alternativa la compilarea repetata a aceleiasi bucati de cod n cazul unor apelari multiple. Unul din avantajele mecanismului JIT apare n clipa n care codul, o data ce a fost compilat, se executa pe diverse
55. Ce este ATLAS?

56. StringBuilder vs String.

This is my second article regarding performance. Most of the people use string everywhere in their code. Actually when doing string concatenation, do you know what exactly you are doing? It has a big drawback mainly in concatenation which can be overcome by StringBuilder. It will give a vast improvement in performance when you use concatenation of string over String.

What is the Exact Difference?


First we will look at what happens when you concatenate two strings. For a rough idea, think like this. In a loop, you are adding few numbers to get a string to give all the numbers.
string returnNumber = ""; for(int i = 0; i<1000; i++) { returnNumber = returnNumber + i.ToString(); }

Here we are defining a string called returnNumber and after that, in the loop we are concatenating the old one with the new to get a string. Do you know when we do like that we are assigning it again and again? I mean it's really like assigning 999 new strings!

Actually the concatenation will create a new string returnNumber, with both old returnNumber andi.ToString(). If we think roughly, how will the performance of the code be? Can you imagine it? No one thinks about this when coding. If we can have something which is to be defined only once and add all the strings into it, what can you say about the performance. That's what StringBuilder does.
StringBuilder returnNumber = new StringBuilder(10000); for(int i = 0; i<1000; i++) { returnNumber.Append(i.ToString()); }

We are creating a StringBuilder of length 10000 in memory where we can add all the strings. This surely won't create a new string each and every time. Actually we are creating a StringBinder, and whenever something is added it will get copied into that memory area. At the end, we can get the string byStringBuilder.ToString(). Here also, it won't create a new string. It will return a string instance that will point to the string inside the StringBuilder. See, how efficient this is? To explain this in a practical manner, I'm not going to analyze IL code or Optimized JIT compiled code. You can see the

differences by running the samples.

Why String? Can't Use StringBinder Everywhere?


No. You can't. When initializing a StringBuilder, you are going down in performance. Also many actions that you do with string can't be done with StringBinder. Actually it is used mostly for situations as explained above. Last week, I showed a person who used StringBuilder to just add two strings together! It's really nonsense. We must really think about the overhead of initialization. In my personal experience, a StringBuilder can be used where more than four or more string concatenations take place. Also if you try to do some other manipulation (like removing a part from the string

, replacing a part in the string, etc.), then it's better not to use StringBuilderat those places. This is because we are anyway creating new strings. Another important issue. We must be careful to guess the size of StringBuilder. If the size which we are going to get is more than what is assigned, it must increase the size. This will reduce its performance.

58. Ce inseamana o clasa template? 59. Ce reprezinta un WebPart?


Reprezinta o colectie de articole, fiind modalitatea ideala de a prezenta vizitatorilor continut tip text. WEBPART-ul este compus dintr-o colectie de articole. Articolul reprezinta o zona de text, cu un preview scurt, avand, optional, atasate resurse grafice. Resursele atasate pot fi de tip imagine (maxim 5 poze) sau video (maxim un film). Atasarea se face cu simple operatiuni tip drag&. Pentru un articol puteti preciza autorul, lisat de cuvinte cheie si descrierea paginii in care se va afisa articolul. De asemenea are si activare, si data de cand este activ.

Un element important este categoria atasata. Se poate defini din interfata de administrare un numar nelimitat de categorii ce pot fi ierarhizate.

Randarea articolului se face tinand cont de principiile SEO friendly, iar webmaster-ul are la dispozitie un link prin care poate verifica cuvintele cheie cele mai potrivite.

Editarea continutului de tip text se face prin intermediul unui editor de text WYSIWYG ( What You See Is What You Get) necesitand minime cunostinte de formatare. Proprietatile unui WEBPART de tip ARTICOL

Ca toate celelalte WEBPART-uri, tipul ARTICOL permite setarea ca meniu de site (si ordinea de afisare), precum si optiunea de afisare stream de tip Feed RSS (compatibil cu RSS2.0). Se poate defini si un layout de pagini (cel mult trei coloane, dimensiunea in pixeli pentru fiecare), astfel incat pagina principala sa arate cat mai aproape de viziunea designer-ului.

Pagina principala a WEBPART-ului tip ARTICOL va contine lista de articole pe coloana specificata de webmaster, precum si alte WEBPART-uri (optional) pe coloanele si in ordinea ce sunt specificate din interafata de adminstrare.

O alta optiune importanta este cea care permite vizitatorilor sa comenteze articolele din WEBPART. Odata activata, devine activa si optiunea de vot, prin care puteti avea feedback de la cititori despre calitatea articolului postat pe site.

WEBPART-ul permite si configurarea numarului de articole afisate in momentul in care este inclus intr-o alta pagina decat cea proprie, precum si

cate articole sa afiseze in arhiva.

60. Cum pot comunica 2 WebPart-uri? 61. Ce este un Master Page?


In Web site development with ASP.NET, the master page is a feature that enables you to define common structure and interface markup elements for your Web site, including headers, footers, style definitions, or navigation bars. The master page can be shared by any of the pages in your Web site, called the Content Page, and removes need to duplicate code for shared elements within your Web site.

62. Pot interactiona dintr-o pagina cu Master Page? Oricum? 63. Cum pot incarca dinamic un control in ASP.NET? 64. Ce este Garbagge Collector?s 65. Ce reprezinta DataBind intr-o pagina web?

Design Patterns

Intrebari generale 4. Ce reprezinta un proces sau thread zombie? 5. Care e diferenta intre un socket UDP si unu TCP/IP?

MS SQL 2000 11. SQL 2005 nu vine din start cu connection=-ul de pe alte calculatoare enabled. Ce trebuie sa fac sa permit aceasta? 12. Care sunt avantajele procedurilor stocate? Cand se recompileaza procedurile stocate pe server?

Intrebari C# cruce ASP.NET 66. Ce inseamna Smart Navigation? 67. Ce inseamna Strong Typed Collection? Exemplu. 68. Ce inseamna un array? 69. Exista pointeri in C#? Daca da unde se pot folosi? 70. Ce inseamna stride?

71. Ce reprezinta ThreadPool? 72. Cum pot la apasarea tastei Enter sa fac submit la o pagina ASP.NET ca si cum as fi apasat un anume buton? 73. Ce reprezinta uncheked? 74. Ce reprezinta unsafe? 75. Ce reprezinta Click and Deploy tehnology?(Publish) 76. Ce este un assembly? Dar o referinta? 77. Care e diferenta intre Typed Data Set si UnTypedDataSet? 78. Poate un DataGrid contine un alt DataGrid? 79. 3 exemple de surse de date pentru un DataList! 80. Ce inseamana cuvantul cheie is? 81. Ce inseamna clientside validation? Ce inseamna browserside validation? 82. Ce este un Windows Service? 83. Ce inseamna "Code Behind"? 84. Cum pot pagina un grid in ASP.NET 2.0 automat?

Intrebari generale 6. Ce este un DTD? 7. Ce este un XML Schema? 8. Ce este un XSL? 9. Ce este XHTML? 10. Ce este un deadlock? Exemplu. 11. Ce este DOM?

Intrebari C# cruce ASP.NET 85. Cum se poate restarta IIS-ul din consola? 86. Ce este Smart navigation? 87. 3 exemple de interfete in C#. 88. Ce este clone? 89. Ce reprezinta boxing si unboxing? 90. Poate avea o functie in C# un nr variabil de parametri? Daca da, cum? 91. 3 moduri in care putem configura un program sau un site web. 92. Moduri in care putem sa face din protocolul Http un protocol cu stari dintr-unul fara stari.

MS SQL 2000 12. Ce reprezinta Delete Cascade?

Intrebari generale: 12. Deadlock. Ce este ? Exemplu. 13. Ce este stiva? Dar heapul? 14. Ce este un HashTable? 15. Ce este recursivitatea? Exemplu. 16. 3 Exemple de algortimi de sortare 17. Ce este un SQL injection? 18. Ce este o conditie de race? Exemplu. 19. Ce este un pointer?

Intrebari C# 93. Ce este tehnica double buffer si la ce foloseste? 94. Ce reprezinta directorul dintr-o site asp.net App_code si la ce se foloseste? 95. Cum se poate transmite un mesaj de tip Email din C#? 96. Ce reprezinta proprietatea Tag a unui control? 97. Se poate deactiva proprietatea View State?