Solved

MyObject obj1 = obj as MyObject;

Posted on 2014-03-03
1
183 Views
Last Modified: 2014-03-11
Can someone tell me what this line of code mean.... MyObject obj1 = obj as MyObject;

class MyObject : IComparable
{
public int ID{ get; set; }
public int CompareTo(object obj)
{
MyObject obj1 = obj as MyObject;
return this.ID.CompareTo(obj1.ID);
}
}

Open in new window

0
Comment
Question by:yguyon28
1 Comment
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 39902123
It's a cast. Ordinarily, you use parentheses and a type name to perform a cast:

e.g.

MyObject obj1 = (MyObject)obj;

Open in new window


This has the consequence that if obj is not actually of type MyObject, or descended from it, then you will encounter an exception. The as operator also performs casts, but it has the added benefit that if the cast will not succeed--that is, if the thing being cast isn't of the type being cast to (or descended from it)--then as will return null. It's a good way to confirm a cast will succeed before working with the casted reference.

A word of warning:  Since as can return null you should be checking for null any time you use as:

e.g.

MyObject obj1 = obj as MyObject;

if (obj1 != null)
{
    // Cast succeeded
}

if (obj1 == null)
{
    // Cast failed
}

Open in new window

0

Featured Post

ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question