Solved

MyObject obj1 = obj as MyObject;

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

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
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…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

762 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

8 Experts available now in Live!

Get 1:1 Help Now