Solved

MyObject obj1 = obj as MyObject;

Posted on 2014-03-03
1
180 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

911 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now