Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all ,


I have dout abt casting in C# let me explain .

I have third party class which return a System.Window.Form.Textbox.


I want to assign this TextBox to My custom textbox Class .

Below is the Eg of my Custom Class


C#
public class TestTextbox : TextBox
 {
     public override Font Font { get { return base.Font; } set { base.Font = value; } }

 }


but i m not able to cast this
C#
TestTextbox txt = (TestTextbox)(Some method Which returns System.Window.Form.Textbox );


What im missing ,


Thanks in Advance.
Posted
Updated 30-Jan-12 20:23pm
v2
Comments
Sergey Alexandrovich Kryukov 31-Jan-12 2:51am    
You are missing... OOP. The answer by Abhinav is correct; I suggest you accept it formally (green button). Is something is not clear, comment his answer.
--SA

You are deriving from TextBox. As a result, you cannot force a cast of a parent into a child class.
This code simply won't work.

You cannot downcast. TestTextBox will have some additional methods which TextBox may not have.
As a result, if you were able to downcast, those methods would not be available.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 31-Jan-12 2:48am    
Abhinav, you should be more precise: this relationship between classes is called "generalization" or "base class (ancestor) -- derived class", not parent/child. Your explanation is correct, I'll case a vote of 4. :-)
--SA
Abhinav S 31-Jan-12 3:20am    
Yes I am aware of generalization SA. :)
Thanks though.
manognya kota 31-Jan-12 2:55am    
Correct..How did i miss my basic?was more bothered at the syntax :(. my +5
Hi,

Please try,

C#
TestTextbox txt =(method Which returns System.Window.Form.Textbox) as  TestTextbox;


Hope this helps.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 31-Jan-12 2:50am    
Totally wrong. Please see the answer by Abhinav for the explanation.
Also, you should not give answer which you did not validate. You could check it up with a compiler in no time, but you preferred to just give an answer which turns out to be a plain simple lie. Please don't do such thing. You got a vote of 1, sorry.
--SA
manognya kota 31-Jan-12 2:53am    
Yup..checked the question again..how did i miss the basic.. :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900