SlideShare une entreprise Scribd logo
1  sur  8
Télécharger pour lire hors ligne
1.Difference between String and StringBuilder

      S.No   String                                  StringBuilder

      1      String class belongs        to   the StringBuilder class belongs to the
             namespace System.                    namespace System.Text.

      2      String class is immutable.              StringBuilder class is mutable.
             Immutable means that the string         Consider the following example:
             cannot be changed. Consider the         class            sampleClass           {
             following                   example:    public     static   void     Main()    {
             class         sampleClass           {   StringBuilder sampleSB = new
             public static void Main() {             StringBuilder("Hai",10);
             string sampleStr =             "Hai";   sampleSB           =         new
             sampleStr          =         "Hello";   StringBuilder("Hello");
             Console.WriteLine(sampleStr);           Console.WriteLine(sampleSB);
             }                                       }
             }                                       }
             Output of this code will be:            Output of this code will be:
             Hello                                   Hello
             In this example, you have created       In this example, you are doing the
             a string called sampleStr. You          same thing. But the string "Hai" will
             have initially assigned the value       be overwritten as "Hello" and no new
             "Hai". And then you try to              strings will be created in the memory.
             overwrite its value with "Hello".
             You get the overwritten value as
             output. But the problem lies in the
             number of strings that get created
             in memory. When you create the
             string as "Hai", this string gets
             created in the memory. When you
             try to change the value to "Hello",
             instead of overwriting the existing
             "Hai" string it will create a new
             string in the memory and assign
             this new string "Hello" to
             sampleStr.


      3      You can directly assign a string to You cannot directly assign a string to
             string class instance. For example, StringBuilder instance. For example,
             String sampleStr = "Hai" is valid. StringBuilder sampleSB = "Hai" will
                                                 lead to the following error:
                                                 "cannot implicitly convert type 'string'
                                                 to    'System.Text.StringBuilder'      "
                                                 You can assign a string to
                                                 StringBuilder using the following
                                                 statement:
                                                 StringBuilder sampleSB = new
                                                 StringBuilder("Hai");

      4      String concatenation is done using String concatenation is done using
+ operator. Here is an example:       Append method. Here is an example:
    class        sampleClass          {   class           sampleClass       {
    public static void Main() {           public    static   void    Main() {
    string sampleStr = "Hello!";          StringBuilder sampleSB = new
    sampleStr += " Good Day!";            StringBuilder("Hello!");
    Console.WriteLine(sampleStr);         sampleSB.Append("Good
    }                                     Day!");
    }                                     Console.WriteLine(sampleSB);
    Output of this code will be:          }
    Hello! Good Day!                      }
    Here you have used += operator        Output of this code will be:
    to perform both concatenation and     Hello! Good Day!
    assignment using single operator.
    You can also use + and =
    separately as shown below:
    sampleStr = sampleStr + " Good
    Day!";


5   During string concatenation, During string concatenation, additional
    additional memory will be memory will be allocated if and only if
    allocated.                   the string buffer's capacity is reached.

6   During string concatenation, If the number of concatenations to be
    additional memory will be done is random or not known, then it is
    allocated if and only if the string recommended to use stringBuilder
    buffer's capacity is reached.

7   You cannot set a limit (specifying    You can set a limit to StringBuilder
    how many strings can be               using the member called capacity
    concatenated) to a string object      which will by default have the value
    using string class.                   16. You can override it to any number.
                                          The maximum value acceptable is
                                          equivalent to MaxValue of Int32. If
                                          you feel that you do not want to
                                          reserve 16 as the capacity then you can
                                          very well redefine it. However the
                                          capacity will dynamically grow based
                                          on the number of strings that you
                                          append.
                                          Here is an example demonstrating the
                                          usage of capacity:
                                          class sampleClass {
                                          public static void Main() {
                                          StringBuilder sampleSB = new
                                          StringBuilder();
                                          Console.WriteLine(
                                          sampleSB.Capacity);
                                          sampleSB.Capacity = 1;
                                          Console.WriteLine(
                                          sampleSB.Capacity);
sampleSB.Append("str1");
                                                   sampleSB.Append("str2");
                                                   Console.WriteLine(
                                                   sampleSB.Capacity);
                                                   }
                                                   }
                                                   Output of this code will be:
                                                   16
                                                   1
                                                   8


2.Difference between Delegate and Interface

      S.No   Delegate                              Interface

      1      Delegates can only be methods. Interface can include both properties
             Here is an example:             and methods.
             delegate void sampleDelegate(); Here is an example for an interface:
                                             interface ItestInterface
                                             {
                                                int paraml {
                                               get; set; }
                                             void sampleMethod();
                                             }

      2      Delegate can be applied to only When a class implements an interface,
             one method at a time            it can implement all the methods
                                             associated with it

      3      You can use a delegate that is You can use an interface only when
             visible in your scope          your class or struct implements it

      4      Within a class, you can implement     Within a class, you can implement an
             the same delegate any number of       interface method only once. In
             times. Assume         that   either   Example2, interface ITestInterface has
             sampleClass1 or sampleClass2 of       a method called sampleMethod().
             Examplel includes a method            When       sampleClass1    implements
             called sampleMethod2( ) with the      ITestInterface        it   implements
             same signature as that of delegate,   sampleMethod() only once. If not, then
             then the same delegate can be         it will end up in error.
             used      to      access      both
             sampleMethod() as well as
             sampleMethod2( )

      5      Delegate can implement any When an interface method is
             method that shares the same implemented, same method name and
             signature as that of the delegate signature has to be overridden

      6      Delegate is mainly used for Interfaces are not used for handling
             handling events             events
7    You need not bother about the         When a class implements an interface,
     other methods available in the        though the class requires only one
     class.You are concerned about         method it has to implement all the
     only the method that matches          methods of the interface
     delegate signature.

8    To access a method using              To access the method, you need an
     delegate, you need not require any    instance of the class which implements
     access to the instance of the class   the interface or you need an interface
     where the method is defined           reference pointing to the method
                                           implemented by the class

9    You can access anonymous You cannot access anonymous
     methods using delegates  methods.Only       named     methods
                              declared in interface can be accessed
                              by the implementing class.

10   When you call a method using a        When you are calling a method using
     delegate, all the method pointers     interface reference, you are directly
     associated with the delegate will     accessing the method of the class that
     be scanned through before the         implements the interface. This is a
     method execution. This is not a       direct method call and it doesn't have
     direct method call as you assume.     any overhead.
     It has a considerable performance
     overhead.

11   Delegates can wrap methods of Accessing sealed types                is   not
     sealed classes.Sealed classes are permissible in interface.
     those which cannot be inherited.

12   Delegates can wrap any method         Class can implement any number of
     matching its signature irrespective   interfaces and it should override only
     of which ever class the method        the methods belonging to those
     belongs to                            interfaces

13   Delegates can wrap static This provision is not available with
     methods. Examplel discussed interfaces .
     above has used the delegate to
     wrap a static method called
     sampleMethod()

14   Delegate cannot       involve    in Interface can inherit other interfaces.
     inheritance.                        When a class implements that
                                         interface, it has to implement all the
                                         methods belonging to the interface and
                                         its inherited interfaces as well.
                                         Here is an example of an interface
                                         inheriting from other interfaces:
                                         interface      IInterface:   IInterface,1
                                         IInterface2
                                         {
                                         void sampleMethod1();
                                          void sampleMethod2();
s}


Example1: Using Delegate
delegate void sampleDelegate( );
class sampleClass1{
static void sampleMethod( ) {
Console.WriteLine(“Executing sampleMethod of sampleClass1”);
}
}
class sampleClass2 {
static void Main( ) {
sampleDelegate dele1 = new sampleDelegate(sampleClass1.sampleMethod);
dele1();
}
}
Example2: Using Interface
interface ITestInterface{
void sampleMethod( );
}
class sampleClass1 : ITestInterface {
void sampleMethod( ) {
Console.WriteLine(“Executing sampleMethod of sampleClass1”);
}
}
class sampleClass2 {
static void Main( ) {
sampleClass1 obj1 = new sampleClass1( );
obj1.sampleMethod( );
}
}


3.Difference between Virtual and Abstract keywords in .NET


      S.No   Virtual                              Abstract

      1      If you feel that the derived class   But if you want to enforce that derived
             may or may not override the base     class must override the base class
             class method, then you will define   method then you will define the base
             the base class method as virtual.    class    method     as     abstract.
             Consider the following example:      namespace         Application1         {
             namespace      Application1      {   public abstract class abstractClass {
             public class virtualClass {          public abstract void abstractMethod();
             public         virtual        void   }
             virtualMethod(){                     public                             class
             Console.WriteLine("Virtual           derivedClass:abstractClass{
             Method..");                          public override void abstractMethod(){
             }                                    Console.WriteLine("Overridden..");
}                                      }
    public                         class   }
    derivedClass:virtualClass{             public       class      testClass   {
    public         override        void    public    static    void    Main()  {
    virtualMethod(){                       derivedClass       obj    =     new
    Console.WriteLine("Overridden.."       derivedClass();
    );                                     obj.abstractMethod();
    }                                      }
    }                                      }
    public     class     testClass     {   }
    public static void Main() {            Output of this code will be:
    virtualClass     obj      =     new    Overridden..
    virtualClass();
    obj.virtualMethod();
    derivedClass dObj = new
    derivedClass();
    dObj.virtualMethod();
    }
    }
    }
    Output of this code will be:
    Virtual                    Method..
    Overridden..

2   Virtual methods need not be            Abstract methods should compulsorily
    compulsorily overridden. In the        be overridden by the derived class. In
    above example if the derived class     the above example, if the derivedClass
    does not override the method           does not override abstractMethod, then
    virtualMethod, then again the          during compilation you will get the
    code will work.                        following                         error:
                                           'Application1.derivedClass' does not
                                           implement inherited abstract member
                                           'Application1.abstractClass.abstractMe
                                           thod()'

3   To define a base class method to       If you want to define a method as
    be virtual, you need not include       abstract in the base class then the base
    any new definition for the base        class should also be marked as
    class. In the earlier example, you     abstract. Consider the following
    can see that the class virtualClass    example:
    just includes an access modifier       namespace          Application1        {
    followed by the class name. No         public      class    abstractClass     {
    other additional modifiers are         public abstract void abstractMethod();
    required.                              }
                                           }
                                           In this example, abstractClass has an
                                           abstract method. Hence the class in
                                           itself has to be marked abstract. But it
                                           is not done in the above example.
                                           Therefore during compilation, you will
                                           end up in the following error:
                                           'Application1.abstractClass.abstractMe
thod()' is abstract but it is contained in
                                           nonabstract                          class
                                           'Application1.abstractClass'

4   Virtual method can have a method       Abstract methods have only the
    body. In the earlier example,          signature. It cannot have method body.
    virtualMethod of virtualClass has      However the abstract class can include
    method definition like any of the      non-abstract methods and these
    other methods that you define and      methods can have method body
    it is perfectly legal.                 defined. Consider the following
                                           example:
                                           namespace          Application1       {
                                           public abstract class abstractClass {
                                           public abstract void abstractMethod(){
                                           Console.WriteLine("Abstract
                                           method..");
                                           }
                                           }
                                           }
                                           Here you are trying to include method
                                           body for an abstract method. This is
                                           not permissible. Hence during
                                           compilation you will end up in the
                                           following                         error:
                                           "'Application1.abstractClass.abstractM
                                           ethod()' cannot declare a body because
                                           it is marked abstract"

5   Class containing virtual method        Class containing abstract method
    can be instantiated. Here is an        cannot be instantiated. It can only be
    example:                               inherited. Consider the following
    namespace       Application1       {   example:
    public class virtualClass {            namespace           Application1        {
    public          virtual         void   public abstract class abstractClass {
    virtualMethod(){                       public abstract void abstractMethod();
    Console.WriteLine("Virtual             }
    Method..");                            public       class       testClass      {
    }                                      public    static     void    Main()     {
    }                                      abstractClass        obj      =      new
    Public     class      testClass    {   abstractClass();
    public static void Main() {            }
    virtualClass      obj      =    new    }
    virtualClass();                        }
    obj.virtualMethod();                   Here you are trying to create an
    }                                      instance of abstract class. This is not
    }                                      possible. Hence during compilation
    }                                      you will end up in the following error:
    Output of this code will be:           "cannot create an instance of the
    Virtual Method…                        abstract      class      or     interface
                                           Application1.abstractClass"

6   Not just methods, virtual modifier Apart from class and method, the
can also be used with properties.   modifer abstract can be associated with
                                                 properties, events and indexers.

      7      There is a restriction when using   Abstract modifiers also have a
             virtual modifer. You cannot use     restriction. They cannot be used along
             this modifer along with static or   with static or virtual or override
             abstract or override modifiers.     modifiers.


And, further updates on difference between questions and answers, please visit my blog @
http://onlydifferencefaqs.blogspot.in/

Contenu connexe

Similaire à OOPs difference faqs- 4

javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
fedcoordinator
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 

Similaire à OOPs difference faqs- 4 (20)

String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Text processing
Text processingText processing
Text processing
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
Java String
Java String Java String
Java String
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
14 ruby strings
14 ruby strings14 ruby strings
14 ruby strings
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Java string handling
Java string handlingJava string handling
Java string handling
 
24_2-String and String Library.pptx
24_2-String and String Library.pptx24_2-String and String Library.pptx
24_2-String and String Library.pptx
 
String.ppt
String.pptString.ppt
String.ppt
 

Plus de Umar Ali

Plus de Umar Ali (20)

Difference between wcf and asp.net web api
Difference between wcf and asp.net web apiDifference between wcf and asp.net web api
Difference between wcf and asp.net web api
 
Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()
 
Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4
 
Difference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvcDifference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvc
 
Difference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvcDifference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvc
 
ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1
 
Link checkers 1
Link checkers 1Link checkers 1
Link checkers 1
 
Affiliate Networks Sites-1
Affiliate Networks Sites-1Affiliate Networks Sites-1
Affiliate Networks Sites-1
 
Technical Video Training Sites- 1
Technical Video Training Sites- 1Technical Video Training Sites- 1
Technical Video Training Sites- 1
 
US News Sites- 1
US News Sites- 1 US News Sites- 1
US News Sites- 1
 
How to create user friendly file hosting link sites
How to create user friendly file hosting link sitesHow to create user friendly file hosting link sites
How to create user friendly file hosting link sites
 
Weak hadiths in tamil
Weak hadiths in tamilWeak hadiths in tamil
Weak hadiths in tamil
 
Bulughul Maram in tamil
Bulughul Maram in tamilBulughul Maram in tamil
Bulughul Maram in tamil
 
Asp.net website usage and job trends
Asp.net website usage and job trendsAsp.net website usage and job trends
Asp.net website usage and job trends
 
Indian news sites- 1
Indian news sites- 1 Indian news sites- 1
Indian news sites- 1
 
Photo sharing sites- 1
Photo sharing sites- 1 Photo sharing sites- 1
Photo sharing sites- 1
 
File hosting search engines
File hosting search enginesFile hosting search engines
File hosting search engines
 
Ajax difference faqs compiled- 1
Ajax difference  faqs compiled- 1Ajax difference  faqs compiled- 1
Ajax difference faqs compiled- 1
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

OOPs difference faqs- 4

  • 1. 1.Difference between String and StringBuilder S.No String StringBuilder 1 String class belongs to the StringBuilder class belongs to the namespace System. namespace System.Text. 2 String class is immutable. StringBuilder class is mutable. Immutable means that the string Consider the following example: cannot be changed. Consider the class sampleClass { following example: public static void Main() { class sampleClass { StringBuilder sampleSB = new public static void Main() { StringBuilder("Hai",10); string sampleStr = "Hai"; sampleSB = new sampleStr = "Hello"; StringBuilder("Hello"); Console.WriteLine(sampleStr); Console.WriteLine(sampleSB); } } } } Output of this code will be: Output of this code will be: Hello Hello In this example, you have created In this example, you are doing the a string called sampleStr. You same thing. But the string "Hai" will have initially assigned the value be overwritten as "Hello" and no new "Hai". And then you try to strings will be created in the memory. overwrite its value with "Hello". You get the overwritten value as output. But the problem lies in the number of strings that get created in memory. When you create the string as "Hai", this string gets created in the memory. When you try to change the value to "Hello", instead of overwriting the existing "Hai" string it will create a new string in the memory and assign this new string "Hello" to sampleStr. 3 You can directly assign a string to You cannot directly assign a string to string class instance. For example, StringBuilder instance. For example, String sampleStr = "Hai" is valid. StringBuilder sampleSB = "Hai" will lead to the following error: "cannot implicitly convert type 'string' to 'System.Text.StringBuilder' " You can assign a string to StringBuilder using the following statement: StringBuilder sampleSB = new StringBuilder("Hai"); 4 String concatenation is done using String concatenation is done using
  • 2. + operator. Here is an example: Append method. Here is an example: class sampleClass { class sampleClass { public static void Main() { public static void Main() { string sampleStr = "Hello!"; StringBuilder sampleSB = new sampleStr += " Good Day!"; StringBuilder("Hello!"); Console.WriteLine(sampleStr); sampleSB.Append("Good } Day!"); } Console.WriteLine(sampleSB); Output of this code will be: } Hello! Good Day! } Here you have used += operator Output of this code will be: to perform both concatenation and Hello! Good Day! assignment using single operator. You can also use + and = separately as shown below: sampleStr = sampleStr + " Good Day!"; 5 During string concatenation, During string concatenation, additional additional memory will be memory will be allocated if and only if allocated. the string buffer's capacity is reached. 6 During string concatenation, If the number of concatenations to be additional memory will be done is random or not known, then it is allocated if and only if the string recommended to use stringBuilder buffer's capacity is reached. 7 You cannot set a limit (specifying You can set a limit to StringBuilder how many strings can be using the member called capacity concatenated) to a string object which will by default have the value using string class. 16. You can override it to any number. The maximum value acceptable is equivalent to MaxValue of Int32. If you feel that you do not want to reserve 16 as the capacity then you can very well redefine it. However the capacity will dynamically grow based on the number of strings that you append. Here is an example demonstrating the usage of capacity: class sampleClass { public static void Main() { StringBuilder sampleSB = new StringBuilder(); Console.WriteLine( sampleSB.Capacity); sampleSB.Capacity = 1; Console.WriteLine( sampleSB.Capacity);
  • 3. sampleSB.Append("str1"); sampleSB.Append("str2"); Console.WriteLine( sampleSB.Capacity); } } Output of this code will be: 16 1 8 2.Difference between Delegate and Interface S.No Delegate Interface 1 Delegates can only be methods. Interface can include both properties Here is an example: and methods. delegate void sampleDelegate(); Here is an example for an interface: interface ItestInterface { int paraml { get; set; } void sampleMethod(); } 2 Delegate can be applied to only When a class implements an interface, one method at a time it can implement all the methods associated with it 3 You can use a delegate that is You can use an interface only when visible in your scope your class or struct implements it 4 Within a class, you can implement Within a class, you can implement an the same delegate any number of interface method only once. In times. Assume that either Example2, interface ITestInterface has sampleClass1 or sampleClass2 of a method called sampleMethod(). Examplel includes a method When sampleClass1 implements called sampleMethod2( ) with the ITestInterface it implements same signature as that of delegate, sampleMethod() only once. If not, then then the same delegate can be it will end up in error. used to access both sampleMethod() as well as sampleMethod2( ) 5 Delegate can implement any When an interface method is method that shares the same implemented, same method name and signature as that of the delegate signature has to be overridden 6 Delegate is mainly used for Interfaces are not used for handling handling events events
  • 4. 7 You need not bother about the When a class implements an interface, other methods available in the though the class requires only one class.You are concerned about method it has to implement all the only the method that matches methods of the interface delegate signature. 8 To access a method using To access the method, you need an delegate, you need not require any instance of the class which implements access to the instance of the class the interface or you need an interface where the method is defined reference pointing to the method implemented by the class 9 You can access anonymous You cannot access anonymous methods using delegates methods.Only named methods declared in interface can be accessed by the implementing class. 10 When you call a method using a When you are calling a method using delegate, all the method pointers interface reference, you are directly associated with the delegate will accessing the method of the class that be scanned through before the implements the interface. This is a method execution. This is not a direct method call and it doesn't have direct method call as you assume. any overhead. It has a considerable performance overhead. 11 Delegates can wrap methods of Accessing sealed types is not sealed classes.Sealed classes are permissible in interface. those which cannot be inherited. 12 Delegates can wrap any method Class can implement any number of matching its signature irrespective interfaces and it should override only of which ever class the method the methods belonging to those belongs to interfaces 13 Delegates can wrap static This provision is not available with methods. Examplel discussed interfaces . above has used the delegate to wrap a static method called sampleMethod() 14 Delegate cannot involve in Interface can inherit other interfaces. inheritance. When a class implements that interface, it has to implement all the methods belonging to the interface and its inherited interfaces as well. Here is an example of an interface inheriting from other interfaces: interface IInterface: IInterface,1 IInterface2 { void sampleMethod1(); void sampleMethod2();
  • 5. s} Example1: Using Delegate delegate void sampleDelegate( ); class sampleClass1{ static void sampleMethod( ) { Console.WriteLine(“Executing sampleMethod of sampleClass1”); } } class sampleClass2 { static void Main( ) { sampleDelegate dele1 = new sampleDelegate(sampleClass1.sampleMethod); dele1(); } } Example2: Using Interface interface ITestInterface{ void sampleMethod( ); } class sampleClass1 : ITestInterface { void sampleMethod( ) { Console.WriteLine(“Executing sampleMethod of sampleClass1”); } } class sampleClass2 { static void Main( ) { sampleClass1 obj1 = new sampleClass1( ); obj1.sampleMethod( ); } } 3.Difference between Virtual and Abstract keywords in .NET S.No Virtual Abstract 1 If you feel that the derived class But if you want to enforce that derived may or may not override the base class must override the base class class method, then you will define method then you will define the base the base class method as virtual. class method as abstract. Consider the following example: namespace Application1 { namespace Application1 { public abstract class abstractClass { public class virtualClass { public abstract void abstractMethod(); public virtual void } virtualMethod(){ public class Console.WriteLine("Virtual derivedClass:abstractClass{ Method.."); public override void abstractMethod(){ } Console.WriteLine("Overridden..");
  • 6. } } public class } derivedClass:virtualClass{ public class testClass { public override void public static void Main() { virtualMethod(){ derivedClass obj = new Console.WriteLine("Overridden.." derivedClass(); ); obj.abstractMethod(); } } } } public class testClass { } public static void Main() { Output of this code will be: virtualClass obj = new Overridden.. virtualClass(); obj.virtualMethod(); derivedClass dObj = new derivedClass(); dObj.virtualMethod(); } } } Output of this code will be: Virtual Method.. Overridden.. 2 Virtual methods need not be Abstract methods should compulsorily compulsorily overridden. In the be overridden by the derived class. In above example if the derived class the above example, if the derivedClass does not override the method does not override abstractMethod, then virtualMethod, then again the during compilation you will get the code will work. following error: 'Application1.derivedClass' does not implement inherited abstract member 'Application1.abstractClass.abstractMe thod()' 3 To define a base class method to If you want to define a method as be virtual, you need not include abstract in the base class then the base any new definition for the base class should also be marked as class. In the earlier example, you abstract. Consider the following can see that the class virtualClass example: just includes an access modifier namespace Application1 { followed by the class name. No public class abstractClass { other additional modifiers are public abstract void abstractMethod(); required. } } In this example, abstractClass has an abstract method. Hence the class in itself has to be marked abstract. But it is not done in the above example. Therefore during compilation, you will end up in the following error: 'Application1.abstractClass.abstractMe
  • 7. thod()' is abstract but it is contained in nonabstract class 'Application1.abstractClass' 4 Virtual method can have a method Abstract methods have only the body. In the earlier example, signature. It cannot have method body. virtualMethod of virtualClass has However the abstract class can include method definition like any of the non-abstract methods and these other methods that you define and methods can have method body it is perfectly legal. defined. Consider the following example: namespace Application1 { public abstract class abstractClass { public abstract void abstractMethod(){ Console.WriteLine("Abstract method.."); } } } Here you are trying to include method body for an abstract method. This is not permissible. Hence during compilation you will end up in the following error: "'Application1.abstractClass.abstractM ethod()' cannot declare a body because it is marked abstract" 5 Class containing virtual method Class containing abstract method can be instantiated. Here is an cannot be instantiated. It can only be example: inherited. Consider the following namespace Application1 { example: public class virtualClass { namespace Application1 { public virtual void public abstract class abstractClass { virtualMethod(){ public abstract void abstractMethod(); Console.WriteLine("Virtual } Method.."); public class testClass { } public static void Main() { } abstractClass obj = new Public class testClass { abstractClass(); public static void Main() { } virtualClass obj = new } virtualClass(); } obj.virtualMethod(); Here you are trying to create an } instance of abstract class. This is not } possible. Hence during compilation } you will end up in the following error: Output of this code will be: "cannot create an instance of the Virtual Method… abstract class or interface Application1.abstractClass" 6 Not just methods, virtual modifier Apart from class and method, the
  • 8. can also be used with properties. modifer abstract can be associated with properties, events and indexers. 7 There is a restriction when using Abstract modifiers also have a virtual modifer. You cannot use restriction. They cannot be used along this modifer along with static or with static or virtual or override abstract or override modifiers. modifiers. And, further updates on difference between questions and answers, please visit my blog @ http://onlydifferencefaqs.blogspot.in/