473,769 Members | 6,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with this sample

trying to learn plymorphism.
My sample is

public class Class1
{
public static void Main(string[] args)
{
Cls1 x = new Cls1();
Cls2 y = new Cls2();
Cls3 y = new Cls3();

Object[] coll = new Object[] {x,y,z};

foreach (Object obj in coll)
{
Console.WriteLi ne(obj.Rtn());
// here is the issue.
//How to get the return value of Rtn();
//I want to use the loop and the concept of polymorphism

}
}
}
public class Cls1
{
public string Rtn()
{
return "From Cls1";
}
}
public class Cls2
{
public string Rtn()
{
return "From Cls2";
}
}

public class Cls3
{
public string Rtn()
{
return "From Cls3";
}
}

Nov 26 '06 #1
13 1971
In order to exhibit polymorphism, your classes Cls1, Cls2, Cls3 need to
all derive from a base class with your common method defined.

Declare an abstract base class with one method called Rtn(). Derive
your classes from this class and then during your foreach loop, call
the method on the base class rather than the concrete classes

eg

public abstract MyBaseClass
{
public abstract string Rtn();
}

public class Cls1 : MyBaseClass
{
public override string Rtn()
{
return "From class 1";
}
}
//repeat this for your other classes

when calling the method use

foreach (MyBaseClass c in coll)
{
Console.Writeln ( c.Rtn() );
}

Hope this helps.

ps if you dont want to use an abstract class then you can just create a
concrete base class and mark the method as protected virtual

On Nov 26, 8:23 pm, "Praveen" <prav...@newsgr oup.nospamwrote :
trying to learn plymorphism.
My sample is

public class Class1
{
public static void Main(string[] args)
{
Cls1 x = new Cls1();
Cls2 y = new Cls2();
Cls3 y = new Cls3();

Object[] coll = new Object[] {x,y,z};

foreach (Object obj in coll)
{
Console.WriteLi ne(obj.Rtn());
// here is the issue.
//How to get the return value of Rtn();
//I want to use the loop and the concept of polymorphism

}
}
}

public class Cls1
{
public string Rtn()
{
return "From Cls1";
}
}

public class Cls2
{
public string Rtn()
{
return "From Cls2";
}
}

public class Cls3
{
public string Rtn()
{
return "From Cls3";
}
}
Nov 26 '06 #2
Hi,

Polymorphism exists in .NET via inheritance and interfaces. You haven't
illustrated the use of interfaces in your example, and you've barely
scratched the surface of inheritance. Here's a simple article that you may
want to read:

"Polymorphi sm in object-oriented programming"
http://en.wikipedia.org/wiki/Polymor...ed_programming
Cls3 y = new Cls3();
Your code won't compile because the line above attempts to redefine "y".
foreach (Object obj in coll)
{
Console.WriteLi ne(obj.Rtn());
You can't call obj.Rtn() because obj is of the Type, "System.Object" , which
doesn't provide a method named, "Rtn". You must cast "obj" to a Type that
has a method named, "Rtn":

foreach (object obj in coll)
{
if (obj is Cls1)
Console.WriteLi ne(((Cls1) obj).Rtn());
else if (obj is Cls2)
Console.WriteLi ne(((Cls2) obj).Rtn());
else if (obj is Cls3)
Console.WriteLi ne(((Cls3) obj).Rtn());
}

Obviously, this isn't very dynamic at all.

Since you'd like to late-bind to an instance of Cls1, Cls2 and Cls3 to call
"Rtn", a method which each of these classes has in common with the same
signature, you could use an interface:

interface IReturn
{
string Rtn();
}

class Cls1 : IReturn
{
public string Rtn() { return "From Cls1"; }
}

class Cls2 : IReturn
{
public string Rtn() { return "From Cls2"; }
}

....

And you can use the interface as such:

IReturn[] returningColl = new IReturn[] {
new Cls1(), new Cls2()
};

foreach (IReturn returningObject in returningColl)
Console.WriteLi ne(returningObj ect.Rtn());

--
Dave Sexton

"Praveen" <pr*****@newsgr oup.nospamwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
trying to learn plymorphism.
My sample is

public class Class1
{
public static void Main(string[] args)
{
Cls1 x = new Cls1();
Cls2 y = new Cls2();
Cls3 y = new Cls3();

Object[] coll = new Object[] {x,y,z};

foreach (Object obj in coll)
{
Console.WriteLi ne(obj.Rtn());
// here is the issue.
//How to get the return value of Rtn();
//I want to use the loop and the concept of polymorphism

}
}
}
public class Cls1
{
public string Rtn()
{
return "From Cls1";
}
}
public class Cls2
{
public string Rtn()
{
return "From Cls2";
}
}

public class Cls3
{
public string Rtn()
{
return "From Cls3";
}
}

Nov 26 '06 #3
Hi Praveen,

You cannot invoke the Rtn method from the variable of type object without
casting it to the appropriate class type.
But since you want to use polymorphism, you dont want to cast it.

polymorphism can be applied in this case, can be accomplished in the
following ways

--Derive Cls1, Cls2 and Cls3 from a common base type.
The base type should have a virtual method Rtn which you should override
in each of the classes Cls1, Cls2 amd Cls3.

Example:
class BaseType
{
protected virtual string Rtn()
{
return String.Empty;
}

}
class Cls1 : BaseType
{
protected override string Rtn()
{
return "From Cls1";;
}
}
Use BaseType[] instead of object[]

OR

--Create a particular Interface which defines the method Rtn.
Implement the Rtn method in each of the classes Cls1, Cls2 amd Cls3.
interface IBaseType
{
string Rtn();
}
class Cls1 : IBaseType
{
public string Rtn()
{
return "From Cls1";;
}
}
Use IBaseType[] instead of object[]

Regards,
Hameer Saleem
"Praveen" wrote:
trying to learn plymorphism.
My sample is

public class Class1
{
public static void Main(string[] args)
{
Cls1 x = new Cls1();
Cls2 y = new Cls2();
Cls3 y = new Cls3();

Object[] coll = new Object[] {x,y,z};

foreach (Object obj in coll)
{
Console.WriteLi ne(obj.Rtn());
// here is the issue.
//How to get the return value of Rtn();
//I want to use the loop and the concept of polymorphism

}
}
}
public class Cls1
{
public string Rtn()
{
return "From Cls1";
}
}
public class Cls2
{
public string Rtn()
{
return "From Cls2";
}
}

public class Cls3
{
public string Rtn()
{
return "From Cls3";
}
}

Nov 26 '06 #4
Praveen... Polymorphism, having more than one form, can be implemented
using
interfaces, abstract classes or events. Whenever I see a long switch in
code, I
start thinking about a polymorphic solution. This tutorial may help:

http://www.geocities.com/jeff_louie/oop.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 26 '06 #5
Hi Jeff,

I don't think that "events" have anything to do with "implementi ng"
polymorphism.

--
Dave Sexton

"Jeff Louie" <an*******@devd ex.comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Praveen... Polymorphism, having more than one form, can be implemented
using
interfaces, abstract classes or events. Whenever I see a long switch in
code, I
start thinking about a polymorphic solution. This tutorial may help:

http://www.geocities.com/jeff_louie/oop.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***

Nov 26 '06 #6
Hi Dave... IMHO, events/delegates can be looked at as type safe pointers
to
polymorphic methods.

http://www.geocities.com/jeff_louie/oop31.htm
http://msdn2.microsoft.com/en-us/library/ms173173.aspx

It took me a while to understand this, so that is why I am sticking my
neck out
here to so state this.

Regards,
Jeff
>I don't think that "events" have anything to do with "implementi ng"
polymorphism.<

*** Sent via Developersdex http://www.developersdex.com ***
Nov 26 '06 #7
Hi Jeff,

I'll agree with you that delegates implement polymorphism since they can be
late-bound to their targets, but not events. Events must be part of an
interface, which is already polymorphic in nature. It's the delegates
registered with the events that are polymorphic, not the event itself.

--
Dave Sexton

"Jeff Louie" <an*******@devd ex.comwrote in message
news:OZ******** ******@TK2MSFTN GP02.phx.gbl...
Hi Dave... IMHO, events/delegates can be looked at as type safe pointers
to
polymorphic methods.

http://www.geocities.com/jeff_louie/oop31.htm
http://msdn2.microsoft.com/en-us/library/ms173173.aspx

It took me a while to understand this, so that is why I am sticking my
neck out
here to so state this.

Regards,
Jeff
>>I don't think that "events" have anything to do with "implementi ng"
polymorphism.<

*** Sent via Developersdex http://www.developersdex.com ***

Nov 26 '06 #8
Hi Dave.. This is how I see it. Events and Delegates are intertwined in
NET. In
general they are often used in tandom. Delegates are type safe pointers
to a
polymorphic method. Events are used to simplify the use of Delegates.
When
you fire an event you are calling one or more polymorphic methods. This
type of
semantic debate is important but clouds the concept that polymorphism is
not
limited to interfaces and abstract classes in .NET.

I am trying to say that you can implement polymorphic behaviour in .NET
using
events _and delegates_. To some, this idea is new and may be an "aha"
moment.
I apologize if I was not clear in my original post.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 26 '06 #9
Hi Jeff,
When
you fire an event you are calling one or more polymorphic methods. This
type of
semantic debate is important but clouds the concept that polymorphism is
not
limited to interfaces and abstract classes in .NET.
I disagree.

My point is that delegates are providing the polymorphism, not the events.
Events are just a construct that aggregates delegates for private
invocation.

When you write, "you can implement polymorphic behaviour in .NET using
events _and delegates_.", I disagree that "events" have anything to do with
it. Delegates being added to an "event" are polymorphic regardless. Adding
delegates to an event does not provide any further polymorphic aspects to
the already late-bound delegates. An event itself, being part of a class
definition or interface, may be polymorphic in the sense that it's
implemented or inherited, just like a public property. Public properties
alone are not polymorphic and neither are events.

I think the key here is that Typed delegates derive from System.Delegate ,
which is why delegates are polymorphic - inheritance. Events are not
objects, so they cannot be polymorphic.

To say that you can use events to implement polymorphism is like saying you
can use public properties to implement polymorphism, when in fact it's
actually inheritance and interfaces that are required for polymorphism, not
the class members.

--
Dave Sexton

"Jeff Louie" <an*******@devd ex.comwrote in message
news:uQ******** ******@TK2MSFTN GP03.phx.gbl...
Hi Dave.. This is how I see it. Events and Delegates are intertwined in
NET. In
general they are often used in tandom. Delegates are type safe pointers
to a
polymorphic method. Events are used to simplify the use of Delegates.
When
you fire an event you are calling one or more polymorphic methods. This
type of
semantic debate is important but clouds the concept that polymorphism is
not
limited to interfaces and abstract classes in .NET.

I am trying to say that you can implement polymorphic behaviour in .NET
using
events _and delegates_. To some, this idea is new and may be an "aha"
moment.
I apologize if I was not clear in my original post.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***

Nov 26 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2530
by: Henri Schomäcker | last post by:
Hi folks, I am developing a apache2 so module in c++. At the moment, I'm trying to get it to compile with automake & friends, but don't get it to work. I tried to modify the example in the programmer-docs. I created a simple c++ project and deleted the src subdir and copied my sourcecode files into the basedir. (That's not where I want to let them in the end, but I thought it might be easier in the beginning) Then I copied the sample...
5
1563
by: franklini | last post by:
i cant seem to figure out what is wrong with this class. it has to do with the input/output stream override. please can somebody help me. #include <iostream> #include <string> #include <vector> #include <cmath> using namespace std;
1
4362
by: jase_dukerider | last post by:
Hi I have an assignment to hand in shortly for which I am after some guidance. The task is to read a WAV file, request a fade in /out time for the track from the user and the do the fade by modifying the binary file then writing it as a new file I have attached my code so far but do not know how to do the fade and how to write it as a new file. Please help! #include <stdio.h> #include <stdlib.h> #include <string.h>
0
1686
by: Henry Reardon | last post by:
I just installed DB2 Personal Developer's Edition V8.2 (FP7) over my old DB2 V7.2 instance but I'm having some problems. Can anyone help? The first problem is that my migration didn't go too well. I got this during the setup wizard: The migration of the instance "DB2" has failed. The return value is "-2". When I looked at the databases in the Control Center, they all seemed to be there, including the ones created during the install...
23
3284
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application to create certain textboxes, labels, and combo boxes? Any ideas would be appreciated. Thanks
4
2430
by: Tarun Mistry | last post by:
Hi all, I have posted this in both the c# and asp.net groups as it applies to both (apologies if it breaks some group rules). I am making a web app in asp.net using c#. This is the first fully OO application I will be making, also my first .NET application, so im looking for any help and guidance. Ok, my problems are todo with object and database abstraction, what should i do.
11
2121
by: Bryan Kyle | last post by:
Hi All, I'm fairly new to C# and Generics and I'm wondering if anyone has some suggestions for me. I'm trying to implement a simple DAO framework using generics to keep my code as clean as I can, however I'm getting an error with what seems to me to be correct code. The error I'm getting is: Error 1 Cannot implicitly convert type 'Sample.PersonDao' to
0
1759
by: Hennie Coertze | last post by:
Good day, My knowledge of XML is next to none and I only have one XSL code to use. I also assume I may be using incorrect jargon and hope you will understand what I need. I have an XSL style sheet to convert the XML flat file. I need to change the style sheet so it groups certain data together under one heading. I need to be able to do this as the system I upload the file to do not accept the information as presented and continuously...
3
11263
by: buntyindia | last post by:
Hi I am creatng a Scrollable Table following is my code. This table is working fine in Mozilla but in IE 6 it is not showing the Scroll Bars.. Please Hellp... Regards, <html> <head></head>
0
9590
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9424
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10000
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.