473,804 Members | 3,250 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic method to return object reference

acb
Hi,

I have a list of different objects in a <List> Structure. There is only
one category of each kind of object.

Current I have the following methods:

public static Flag GetFlagObj()
{
foreach (Thingy s in _Thingies)
{
if (s is Flag)
return (Flag)s;
}
return null;
}

public static Cloth GetFlagObj()
{
foreach (Thingy s in _Thingies)
{
if (s is Cloth)
return (Cloth)s;
}
return null;
}

public static BedSprd GetFlagObj()
{
foreach (Thingy s in _Thingies)
{
if (s is BedSprd)
return (BedSprd)s;
}
return null;
}
Is there a way I could have one generic method that would take as a
parameter the item I wish returned?

Thank you for your help.
Al

Jan 25 '06 #1
12 2268
"acb" <ch******@gmail .com> a écrit dans le message de news:
11************* *********@g47g2 00...legr oups.com...

| I have a list of different objects in a <List> Structure. There is only
| one category of each kind of object.
|
| Current I have the following methods:
|
| public static Flag GetFlagObj()
| {
| foreach (Thingy s in _Thingies)
| {
| if (s is Flag)
| return (Flag)s;
| }
| return null;
| }
|
| public static Cloth GetFlagObj()
| {
| foreach (Thingy s in _Thingies)
| {
| if (s is Cloth)
| return (Cloth)s;
| }
| return null;
| }
|
| public static BedSprd GetFlagObj()
| {
| foreach (Thingy s in _Thingies)
| {
| if (s is BedSprd)
| return (BedSprd)s;
| }
| return null;
| }
|
|
| Is there a way I could have one generic method that would take as a
| parameter the item I wish returned?

Yes, you do it like this :

public static T GetObj<T>()
{
foreach (Thingy s in _Thingies)
{
if (s is T)
return (T) s;
}
return default(T);
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer

Jan 25 '06 #2
possible solution: create generic search method with argument of
required type, disadvantage of this method - generic return value

static List<object> _list = new List<object>();

public static object Find(Type t)
{
return _list.Find(dele gate(object obj)
{
return t.IsAssignableF rom(obj.GetType ());
});
}

Jan 25 '06 #3
As an extension to this; if you are going to have a large number of items
(each of a different type, as suggested by GetObj<T> [GetThingy<T>()
perhaps?]) you could improve performance by using a Dictionary<Type ,
Thingy>; when adding you use obj.GetType() as the key, and when searching
you use typeof(T) - this then gives you hashtable performance.

Also - if thingies can be added / removed outside of the static ctor, I
would strongly advise making this (static) data thread-safe - e.g.

private static Dictionary<Type , Thingy> _Thingies; // init in static ctor

public static T GetThingy<T>()
{
lock(_Thingies) {
return (T) _Thingies[typeof(T)];
}
}

public static void Add(Thingy thingy) {
if(thingy==null ) throw new ArgumentNullExc eption("thingy" ); // need a
non-null thingy to call GetType()
lock(_Thingies) {
_Thingies.Add(t hingy.GetType() , thingy);
}
}

// or - particularly if you accept null values for thingy
public static void Add<T>(T thingy) where T : Thingy {
lock(_Thingies) {
_Thingies.Add(t ypeof(T), thingy);
}
}

(or something like that; code not tested)

Marc
Jan 25 '06 #4
static List<object> _list = new List<object>();

public static T Find<T>()
{
return (T)_list.Find(d elegate(object obj)
{
return (obj is T);
});
}

Jan 25 '06 #5
not important, but I omitted a useful where clause:

public static T GetThingy<T>() where T : Thingy { //...
}

Marc
Jan 25 '06 #6
"Marc Gravell" <mg******@rm.co m> a écrit dans le message de news:
em************* *@TK2MSFTNGP14. phx.gbl...

| As an extension to this; if you are going to have a large number of items
| (each of a different type, as suggested by GetObj<T> [GetThingy<T>()
| perhaps?]) you could improve performance by using a Dictionary<Type ,
| Thingy>; when adding you use obj.GetType() as the key, and when searching
| you use typeof(T) - this then gives you hashtable performance.

Excellent addenda :-))

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jan 25 '06 #7
Some people get a new toy and they just have to use it everywhere!

For the example that you give generics are totally unnecessary and overloads
with "out" parameters will do the job and save you having to type in the
type name in the call.

public static void Get(out X x)
{
foreach(Thingy t in _Thingies)
{
x = t as X;
if( x != null )
return;
}
x = null;
}

X x;
list.Get(out x);

"acb" <ch******@gmail .com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Hi,

I have a list of different objects in a <List> Structure. There is only
one category of each kind of object.

Current I have the following methods:

public static Flag GetFlagObj()
{
foreach (Thingy s in _Thingies)
{
if (s is Flag)
return (Flag)s;
}
return null;
}

public static Cloth GetFlagObj()
{
foreach (Thingy s in _Thingies)
{
if (s is Cloth)
return (Cloth)s;
}
return null;
}

public static BedSprd GetFlagObj()
{
foreach (Thingy s in _Thingies)
{
if (s is BedSprd)
return (BedSprd)s;
}
return null;
}
Is there a way I could have one generic method that would take as a
parameter the item I wish returned?

Thank you for your help.
Al

Jan 25 '06 #8
I'm not sure that your example makes sense here... the original question was
to have a function where the main difference between calls was the type of
thingy (Flag, Cloth, etc). You've essentially written a version that will
*only* gets 1 type: X - i.e. very similar to the code in the OP. If you want
X to be variable, then (unless I'm being really, really slow) you *need*
this to be a generic - i.e. Get<X>

However! You do raise an interesting point; if I refactored this into a
standard TryGet format (but with generics), then I actually *don't* need to
specify T, since this will be inferred by the compiler (via the out param):

public static bool TryGet<T>(out T thingy) where T : Thingy {
lock(_Thingies) {
return _Thingies.TryGe t(typeof(T), out thingy);
}
}

I should then be able to call

Flag f;
MyStaticClass.T ryGet(out f);

This will then infer <Flag> since f is declared as <Flag>

Marc

Jan 25 '06 #9
(previous code didn't compile: this does)

public static bool TryGet<T>(out T thingy) where T : Thingy {
bool found;
Thingy foundItem;
lock (_Thingies) {
found = _Thingies.TryGe tValue(typeof(T ), out foundItem);
}
thingy = (T)foundItem;
return found;
}
Jan 25 '06 #10

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

Similar topics

3
2902
by: Jim Newton | last post by:
hi all, i'm relatively new to python. I find it a pretty interesting language but also somewhat limiting compared to lisp. I notice that the language does provide a few lispy type nicities, but some very important ones seem to be missing. E.g., the multiple class inheritance is great, but there are no generic functions (at least that i can find). If i have classes X, Y, and Z, and subclasses X_sub, Y_sub, and Z_sub respectively.
49
2904
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be appreciated! Thanks! Steve ----------------------------------------------------------------------
15
5371
by: David Lozzi | last post by:
Howdy, I have a function that uploads an image and that works great. I love ..Nets built in upload, so much easier than 3rd party uploaders! Now I am making a public function that will take the path of the uploaded image, and resize it with the provided dimensions. My function is below. The current function is returning an error when run from the upload function: A generic error occurred in GDI+. Not sure what exactly that means. From what...
8
1834
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
5
2286
by: Metaman | last post by:
I'm trying to write a generic method to generate Hashcodes but am having some problems with (generic) collections. Here is the code of my method: public static int GetHashCode(object input) { try { Type objectType = input.GetType(); PropertyInfo properties = objectType.GetProperties();
4
3147
by: Charles Churchill | last post by:
I apologize if this question has been asked before, but after about half an hour of searching I haven't been able to find an answer online. My code is beloiw, with comments pertaining to my question In short my question is why when I pass a generic type directly to the formatObject function it works fine, but when I pass it to the checkText function where it is itself a generic argument, and then it is passed to formatObject, it is seen...
3
3680
by: kim.nolsoee | last post by:
Hi I want to use the Dictionary Classs that will load my own class called KeyClass used as TKey. Here is the code: public class Dictionary { public static void Main()
26
3632
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic delegate type expression in just the right place and a well-named method means we can almost read the code out loud and understand it without even thinking. Note that since 'boxing' and 'unboxing' is involved (I think), you don't get what you...
0
2371
by: =?Utf-8?B?TW9ydGVuIFdlbm5ldmlrIFtDIyBNVlBd?= | last post by:
"Anders Borum" wrote: Hi Anders, I'm afraid the GetMethod() does not currently support filtering on generic parameters so you will have to loop through the existing methods using GetMethods() MethodInfo methods = t.GetMethods();
0
9588
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,...
1
10327
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
10085
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
9161
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...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5527
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...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2999
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.