Monday, April 28, 2014

Typesafe,casting , implicit casting and explicit casting, Strongly Typed ,Week type

C# interview questions :- Explain typesafe,casting , implicit casting and explicit casting ?


Casting is the action of changing an entity of one data type into another.
  class Program
    {
        /* First C# is Type safe langauge. It will not allow you to convert Invalid types at compile time you will get error, even with intellicence will
         give you error message (Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?). But If you want to convert one data type to other you have Type casting and Coversion using Convert class static function for coversion.When you Casting you have to mention the Type to convert but for Conversion you use Convert Class Static function.
         
         But when you convert one dattype to other C# checks the Data loss issue or Compatibility So when you do double to int it will not allow  you For that you shud do Explicit casting. for int to double since no data loss so it will allow no need to do for casting.
         
         */
        static void Main(string[] args)
        {
            //Double d = 100.50;
            //int t;
            //t = d; //error occurr Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

            int x = 3;
            Double y = 3; //Implicit Casting

            Double d1 = 100.50;
            int t1;
            t1 = (int)d1; //Explcit Casting.

            //string s = "amit";
            //int s1 = s; //Error 1      Cannot implicitly convert type 'string' to 'int'

            //See above two error message .
            //string s = "amit";
            //int s1 = (int)s; //Error Cannot implicitly convert type 'string' to 'int'

            //Above type casting is not working

            //string s = "amit";
            //int s1 = Convert.ToInt32(s); //At compile time no error is coming but at run time error is conming because of Invalid type.Because first nobody will convert string to int. FormatExceptin is coming Message:- Input string was not in a correct format.
            //Console.WriteLine(s1);
            //int m = s1 + 9;
            //Console.WriteLine(m);

            string s = "1";
            int s1 = Convert.ToInt32(s);
            Console.WriteLine(s1);
            int m = s1 + 9;
            Console.WriteLine(m); //There is no issue  10 is the output.
            Console.ReadLine();






        }
    }
Difference b/w Cast and convert
1)If you are converting bigger float to int
 //Difference between Convert and Cast
            float f=1234567812345678338888f;
            int i1=(int)f;
            Console.WriteLine(i1);//-2147483648 It will print the minimum value
            Console.WriteLine(" Max value of int" + int.MaxValue + " " + " Minmum value of int" + int.MinValue);// Max value of int2147483647  Minmum value of int-2147483648
            
           // int i2 = Convert.ToInt32(f);//will get OverflowException/Value was either too large or too small for an Int32.

            string str = "100";
            int i3=int.Parse(str);
            Console.WriteLine(i3);//

            //string str1 = "100GGG";
            //int i4 = int.Parse(str1);//Format exception Input string was not in a correct format.
            //Console.WriteLine(i3);//
           // Go for TryParse
            int result1;
            string str1 = "100JJ";
            bool i8 = int.TryParse(str1,out result1);//
            if (i8)//coversion success print value (100) in this case if no than 0
            {
                Console.WriteLine(result1);//
            }
            else
            {
                Console.WriteLine(result1);//
            }
       
            Console.ReadLine();

A Beginner's Tutorial - Type Casting and Type Conversion in C#

Introduction

This small article discusses about type casting in C#. We will look into how implicit type casting works, when will we need explicit casts and how can we enhance our user defined types to support implicit or explicit casts.

Background

Programming in any language will involve manipulation of in-memory data. Accessing this in memory data is via use of variable. We can create specific type of variable to access/manipulate some data. C# allows us to create variables of many types but, being a statically typed language, it does not allow us to assign the value of one type of variable into another type of variables.
From the compiler's perspective, assigning value of one type of variable to another is perhaps not a valid operation(except for implicit casts). This also makes sense since the representation of actual data differ from type to type. But as a developer we know and cn understand the logical relationship and conversion between data types. In a lot of cases, it is almost inevitable to avoid this value assignment from one data type to another.
For the above mentioned reasons, C# has provided the possibility of casting one data type to another. Not only that, it also provides us the flexibility to take full control over casting in our hands(user defined conversions). Along with that it has a lot of Helper classes built in the Library that provides most of the frequently needed casting operations.

Using the code

Let us look at different ways of casting/conversion possible in C#. 

Implicit casts

Let us start by looking into the conversions that are done automatically by C#. Implicit casts are the casts that does not require the programmer to do an explicit conversion. One data type can simply be assigned to another. There are some rules that govern the implicit cast.
1.       Built-in numeric types, widening conversions.
2.       Reference types, Derived class to base class.
The built in numeric types can be assigned to each other if a narrow type is being assigned to wider type. This is possible because the compiler know that the only problem in such operations is that a little more memory will be needed to hold this type and no data will be truncated or lost. So the following conversion will not need any explicit cast. 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
int i = 10;
long l = i;
Secondly, If we try to assign a value from derived class to a base class it will work. that is because a derived class always is-a base class. Also, from a memory perspective a base class variable pointing to a derived class object can safely access the base class part of the object in memory without any problem. SO following code will work without needing any explicit casts.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
class Base
{
 
}
 
class Derived : Base
{
 
}   
 
class Program
{
    static void Main(string[] args)
    {
        Derived d = new Derived();
        Base b = d;      
    }
}
Other then these two possible scenarios, all the conversions will create compile time errors. Still, If we need to perform the conversions, we will have to use explicit casting/conversion.

Explicit casts

If we find ourselves in need of conversion that is either narrowing conversion or conversion between unrelated types then we will have to use explicit conversions. Using explicit conversions we are actually letting the compiler know that we know there is possible information loss but still we need to make this conversion. So if we need to convert a long type to an integer type we need to cast it explicitly.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
long l = 10;
int i = (int)l;
On similar lines, if we need to cast a base class to a derived class I will have to cast it explicitly.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
Base b = new Base();
Derived d = (Derived)b;
Explicit casting actually tells the compiler that we know about possible information loss/mismatch but still we need to perform this cast. This is ok for inbuilt numeric types but in case of reference types, there is a possibility that the types are not at all compatible i.e. casting from one type to another is not at all possible. For example casting a string "abc" to Integer is not possible.
Such casting expressions will compile successfully but they will fail at run-time. What C# compiler does it that it checks whether these two types are cast compatible or not and if not it raises an exception InvalidCastException.

'is' and 'as' operators

So whenever we are using explicit casts, it is always a good idea to wrap the cast inside a try-catch block. C# also provides is and as operators which are helpful in performing explicit casts in an exception safe manner. 
The is operator checks whether the type being casted from is compatible to the type being casted to and returns aboolean value. So the exception safe way to perform an explicit cast using is operator would be 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
static void Main(string[] args)
{   
    // CASE 1 *****
    // This will work fine as o1 is actually an int
    object o1 = 1;
    int i = (int)o1;
 
    // CASE 2 *****
    // This wont work because o2 is not an int so we need 
    // to have an is oprerator before the actual cast
    object o2 = "1";
    int j;
 
    if (o2 is int)
    {
        j = (int)o2;
    }
 
    // CASE 3 *****
    // We can never know what is the atual type of 
    // an object at runtime so its always better to use 
    // is operator, rewriting the first case
    object o3 = 1;
    int k;
 
    if (o3 is int)
    {
        k = (int)o3;
    }
}
Case 1 in the above code snippet will throw an exception is o1 is assigned to some type that is not int. the other 2 cases are exception safe and will only perform the cast if the types are compatible for casting.
There is one small performance issue in using is operator. Case 3 in above code snippet will work fine but it involves accessing the object twice. Once for checking the compatibility i.e. the is operator and secondly to actually extracting out the value i.e. casting. can we not have something like - "Check the compatibility and if compatible perform the cast" in one single operation. That is where the as operator comes in picture.
The as operator checks the compatibility and if its OK it will perform the cast too. If the cast is not compatible or unsuccessful then the result will be null. so the above cast can be rewritten using the as operator
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
object o3 = 1;
int? k = o3 as int?;
 
if (k != null)
{
    //use k for whatever we want to
    Console.WriteLine(k.Value);
}
Note: The important thing to note here is that the as operator can only be used with reference types. This is the reason we used nullable int in the above example.
So if we need to have an exception safe casting, we can use is or as operator. We should use is operator if the target type is a value type and as operator if the target type is a reference type.

User defined conversions

C# also provides the flexibility for defining conversions on classes and structs so that they can be converted to and from other. The conversion operators simply contains the logic of how the conversion should happen. We can define these conversion operators to be implicit or explicit. If we define them implicit the conversion will happen without needing as explicit cast. if we define it as explicit the casting will be required.
Let us try to see how we can implement these conversion operations. Let us implement a small class Rational to hold rational number. We will then define two conversion operations. Int to Rational (an implicit conversion) andRational to double (an explicit conversion).
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
class Rational
{
    int numerator;
    int denominator;
 
    public Rational(int num, int den)
    {
        numerator = num;
        denominator = den;
    }
 
    public static implicit operator Rational(int i)
    {
        // since the rational equivalant of an int has 1 as denominator
        Rational rational = new Rational(i, 1);
 
        return rational;
    }
 
    public static explicit operator double(Rational r)
    {
        double result = ((double)r.numerator) / r.denominator;
        return result;
    }
 
}
And now let us see how we can use these conversion operators to perform actual conversions.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
static void Main(string[] args)
{   
    // Conversion from int to rational is implicit
    Rational r1 = 23;
 
    // Conversion from rational to double is explicit
    Rational r2 = new Rational(3, 2);
    double d = (double)r2;
}
Before wrapping up, there is one more thing that the beginners should be aware of. there are a lot of helper classes and helper functions available in C# to perform the frequently needed conversions. It is always a good idea to refer to the documentation to achieve the desired conversions before putting in the code for conversions. Following code snippet shows how we can convert string to int using Convert class.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
static void Main(string[] args)
{  
    string s = "123";
 
    try
    {
        int i = Convert.ToInt32(s);
    }
    catch (Exception ex)
    {
        // Pokemon exception handling, ideally rectification 
        // code and logging should be done here
    }    
}

Base b = new Base();
Derived d = (Derived)b;
 
You write explicit cast for reference type but above statement leads to run time exception. when I checked the Exception Message I am not getting meaningful information.
 
I did lot of research on that and come to know You can do explicit cast only if it like below 
 
Base b = new Base();
b = new Derived();
Derived d1 = (Derived)b;
We can convert Base to derived type only If base class hold the reference of derived class object.
 
class Base
        {
            public int num1 { get; set; }
        }

        class Derived : Base
        {
            public int num2 { get; set; }
        }

        class Program1
        {
            static void Main(string[] args)
            {
                //Base b = new Base();
                ////Explicit Conversion

               
             //   Derived d = (Derived)b;

                Base b = new Base();
                b = new Derived();
                Derived d1 = (Derived)b;
            }
        }
 namespace 1
{
    class Base
        {
            public int num1 { get; set; }
        }

        class Derived : Base
        {
            public int num2 { get; set; }
        }

        class Program1
        {
            static void Main(string[] args)
            {/*If we try to assign a value from derived class to a base class it will work. that is because a derived class always is-a base class. Also, from a memory perspective a base class variable pointing to a derived class object can safely access the base class part of the object in memory without any problem. SO following code will work without needing any explicit casts.
              * */
                Derived d1 = new Derived(); //Implicit cast
                Base b = d1;
                b.num1 = 2;
             
                //Base b = new Base();
                ////Explicit Conversion
                //Derived d = (Derived)b;         

              
                //Base b2 = new Derived();
                //Derived d2 = b2;//Explicit Cast //Error    1    Cannot implicitly convert type 'KudVenkatCsharp.Base' to 'KudVenkatCsharp.Derived'. An explicit conversion exists (are you missing a cast?)  
                //d2.num1=2;
                //d2.num2 = 9;
                Base b3 = new Derived();
                Derived D3=(Derived)b3;
                Console.WriteLine(D3.num1+D3.num2);
                Console.ReadLine();
            }
        }
  
}
·         Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
·         Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons.  Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.
·         User-defined conversions: User-defined conversions are performed by special methods that you can define to enable explicit and implicit conversions between custom types that do not have a base class–derived class relationship. For more information, see Conversion Operators (C# Programming Guide).
·         Conversions with helper classes: To convert between non-compatible types, such as integers and System.DateTime objects, or hexadecimal strings and byte arrays, you can use the System.BitConverter class, the System.Convert class, and the Parse methods of the built-in numeric types, such as Int32.Parse. For more information, see How to: Convert a byte Array to an int (C# Programming Guide), How to: Convert a String to a Number (C# Programming Guide), and How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide).


http://weblogs.asp.net/fayaz/archive/2011/09/01/casting-and-converting-types-in-net-using-c-part-i.aspx





Q:- Strongly Typed and Week Type
When we say something is strongly typed we mean that the type of the object is known and available.  For example a string is strongly typed when you declare it like so:
string someString = "abc";
When we say a function accepts strongly typed arguments we mean the function accepts a specific set of types as parameters.  For example string concatenation is normally strongly typed like so:
public string Concat ( string string1, string string2 );
In each of the above cases the compiler would generate a compilation error if we attempted to use anything other than a string either for the variable initialization or as a parameter to the Concat function.  (Bear in mind that conversion operators may come into play but ultimately the compiler will raise an error if it can not convert some object to a string).  C# (and C++ and many other languages) is strongly typed because the compiler will detect and flag these errors at compilation time.
In contrast weakly typed languages will either silently ignore bad types or will not catch them until runtime.  VBScript, JavaScript and most interpreted languages are weakly typed because they either silently ignore (or perhaps convert) bad types or raise an error at runtime.  Weakly typed languages are far more difficult to work with as a programmer but provide some late-time binding support that strongly-typed languages just can't handle.
We also use the term weakly typed when we are talking about variables or functions that we don't give an explicit type to.  In .NET we would simply identify them as object types.  Since everything ultimately derives from object anything would work.  In .NET v1.x collections were weakly typed as were many general methods of classes.  For example the following declaration:
ArrayList list = new ArrayList();
list.Add(10);
list.Add("Hello");
list.Add(DateTime.Now);
works because ArrayList is weakly typed because it doesn't really care about the underlying element types.  This has its uses but in general we only store elements of the same type in arrays.  In v2.0 with the addition of generics we can create strongly-typed collections and methods.  The FCL has been updated to strongly type many of the weakly typed classes/methods in the original version (although the weak versions still exist). 
Collection<string> list = new Collection<string>();
list.Add("Hello");
list.Add(10);   //Compilation error because it is strongly typed
In general you should only strive to expose strongly typed classes and methods to give your clients a better idea of what is expected of them and also to avoid having to do a lot of runtime checks to ensure the data you are working with is of the appropriate type.  There are however still cases where weakly typed instances are needed (such as a data source member of a control).  Each has its usages.

Weak with no typing
Assembly languages don’t provide any way of specifying or checking types at all. Everything is just a number.
Weak static typing
C lets you define object types as structures, but it doesn’t do much to enforce or remember them. C automatically convert between many types. C++ and Objective-C go further with the definitions but still don’t enforce the resulting types.
Strong static typing
Java forces you to define all types and checks them with a virtual machine.
Strong dynamic typing
Python, JavaScript and Ruby dynamically infer the types of objects, instead of forcing you to define them, and then enforce those types when the program runs in the interpreter. All dynamically typed languages need a strong typing system at runtime or else they won’t be able to resolve the object types.
Weak dynamic typing
Dynamically inferred types don’t work in a weakly typed language because there aren’t any types to infer.
The static programmer says:
The dynamic programmer says:
“Static typing catches bugs with the compiler and keeps you out of trouble.”
“Static typing only catches some bugs, and you can’t trust the compiler to do your testing.”
“Static languages are easier to read because they’re more explicit about what the code does.”
“Dynamic languages are easier to read because you write less code.”
“At least I know that the code compiles.”
“Just because the code compiles doesn’t mean it runs.”
“I trust the static typing to make sure my team writes good code.”
“The compiler doesn’t stop you from writing bad code.”
“Debugging an unknown object is impossible.”
“Debugging overly complex object hierarchies is unbearable.”
“Compiler bugs happen at midmorning in my office; runtime bugs happen at midnight for my customers.”
“There’s no replacement for testing, and unit tests find more issues than the compiler ever could.”

When we take from datatable by using Label.text=dt.Rows[0][“Name”].ToString(); then if by mistake column name is wrong than you will get Runtime error, there is no compile time error at run time this is checked So that is why  concept of Business object comes into picture. 




Static typing is when your type checking occurs at compile time. You must define a type for your variables inside of your code and any operations you perform on your data would be checked by the compiler.
Dynamic typing is when your type checking occurs at runtime. Instead of errors coming up when you compile your code you will get runtime errors if you try performing operations on incompatible types. However, you will get the benefit of having more versatile functions as they can be written once for multiple data types.
When you have strong typing, you will only be allowed operations on the data by direct manipulation of the objects of that data type.
Weak typing allows you to operate on data without considering its type. Some language do this through pointers. Other languages will convert one of your types to the other before performing the operations. 

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.
There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that
  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.
For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because
  • Amateurs often conflate them with "static" and "dynamic".
  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.
  • Professionals can't agree on exactly what the terms mean.
  • Overall you are unlikely to inform or enlighten your audience.
The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.
By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".
Does one imply the other?
On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:
  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.
  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.
Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.
share|edit|flag


 
***************************************************************************************


    class Employee
    {
        string firstname;
        string lastname;
        public string Firstname { get { return firstname; } set { firstname = value; } }
        public string Lastname { get { return lastname; } set { lastname = value; } }
        public  void PrintName()
        {
            Console.WriteLine("EmployeeName is"+firstname+" "+lastname );
        }
         void PrintName1() //private method
        {
            Console.WriteLine("EmployeeName is" + firstname + " " + lastname);
        }
    }
    class PartTimeEmployee : Employee
    {
        public new void PrintName()
        {
            Console.WriteLine("Part time Employee Name is" + Firstname + " " + Lastname);
        }
    }
    class FullTimeEmployee : Employee
    {      
  
    }
    class A
    {
        public static void Main()
        {
            PartTimeEmployee prt = new PartTimeEmployee { Firstname = "Anil", Lastname = "sharma" };
            prt.PrintName();
            FullTimeEmployee fte = new FullTimeEmployee { Firstname = "Amit", Lastname = "sharma" };
            fte.PrintName();
           //Now there is req that when client see the employee name than he can identify that user is part time or full time. so in specialize class while printinfg name we will add to identify it
            PartTimeEmployee prt1 = new PartTimeEmployee { Firstname = "Anil", Lastname = "sharma" };
            prt1.PrintName(); //but warning is coming saying that child class Printname method hides the inherited base class method. So to overcome this we will add " new " keyword



            FullTimeEmployee fte1 = new FullTimeEmployee { Firstname = "Ram111111", Lastname = "sharma" };
            ((Employee)fte1).PrintName();
            Employee e = new FullTimeEmployee();
           // e.PrintName1();//not coming
            e.PrintName();
            //Here Child class has all information of own and all information that is inherited from base. So we can convert it Base type and can call any of base class method that inherited not the private one

            Employee emp = new Employee { Firstname="K",Lastname="M"};
            FullTimeEmployee f = (FullTimeEmployee)emp;
           //But when we create BAse class object and try to cast in to Child class than you can not you have to explicit cast so that you will no get ay compiple time error but at run time u will egt invalid cast exception.Why because base has its own inofrmation not of child so it become incomplete obj and reference of child will not find any information of its own in base type object.

            
            Console.Read();
        }
    }
//Child class object can ful fill all the responsibility of Parent Class. Parent class object can not ful fill all the res of Child CLass



No comments:

Post a Comment