473,763 Members | 6,666 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Code calls method with wrong signature (object vs object[])

Hello all,

I recently ran into a strange behavior which I don't understand. I
have two 'Add' method which a slightly different signature which they
look like

public void Add( string varName, ScriptVarType type, object value )
public void Add( string varName, ScriptVarType type, object[] values
)

Then in another part of the source base I have the following
declaration

private void Extract( ... )
{
byte[] byteElements;

...

// Where all arguments are assigned before the call is made
ScriptVars.Add( groupsRegEx[1].Value, type, byteElements );
}

The strange item which I don't understand is that instead of call the
method that accepts an array of objects the code is calling the method
where the signature only accepts a single object. Can someone explain
why this is? My guess is since object is the base class of most items
it is also the base class for arrays. Any explanation will be
appreciated. For the time being I will just end up change the method
names to force call to the correct method istead of relying on the
compiler looking at the signature. Thanks

Mark

Aug 15 '06 #1
6 2014
Mark,

The problem here is that arrays are not inherently polymorphic. So, as
a result, the compiler tries to match up the call with the appropriate
function, it sees that byte[] does not cast down to object[], but it does
cast down to object, and that's why the call is made.

You might want to try defining the parameter with the object array as
System.Array, and see if that works.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<Lo*****@hotmai l.comwrote in message
news:11******** *************@b 28g2000cwb.goog legroups.com...
Hello all,

I recently ran into a strange behavior which I don't understand. I
have two 'Add' method which a slightly different signature which they
look like

public void Add( string varName, ScriptVarType type, object value )
public void Add( string varName, ScriptVarType type, object[] values
)

Then in another part of the source base I have the following
declaration

private void Extract( ... )
{
byte[] byteElements;

...

// Where all arguments are assigned before the call is made
ScriptVars.Add( groupsRegEx[1].Value, type, byteElements );
}

The strange item which I don't understand is that instead of call the
method that accepts an array of objects the code is calling the method
where the signature only accepts a single object. Can someone explain
why this is? My guess is since object is the base class of most items
it is also the base class for arrays. Any explanation will be
appreciated. For the time being I will just end up change the method
names to force call to the correct method istead of relying on the
compiler looking at the signature. Thanks

Mark

Aug 15 '06 #2
Two simply workarounds leap to mind:
// 1: since Array is the base of all array implementations
public void Add( string varName, ScriptVarType type, Array values) {}

// 2: (2.0 only) generics;
// note you generally won't have to specify T
// when calling - i.e. declare an int[] vals and call Add(blah, vals);
public void Add<T>( string varName, ScriptVarType type, T[] values) {}

Marc
Aug 16 '06 #3
Lo*****@hotmail .com wrote:
The strange item which I don't understand is that instead of call the
method that accepts an array of objects the code is calling the method
where the signature only accepts a single object. Can someone explain
why this is? My guess is since object is the base class of most items
it is also the base class for arrays. Any explanation will be
appreciated. For the time being I will just end up change the method
names to force call to the correct method istead of relying on the
compiler looking at the signature.
Changing the method names won't help you, as a byte[] isn't an
object[]. The problem is that while *arrays of reference types* are
covariant, arrays of value types aren't. For instance:

string[] stringArray = new string[10];
object[] objectArray = stringArray; // Fine

but

byte[] byteArray = new byte[10];
int[] intArray = byteArray; // No conversion available
object[] objectArray = byteArray; // No conversion available

The other posts give suggested solutions.

Jon

Aug 16 '06 #4
Nicholas,

Thanks for the information as I didn't realize this until now.
Instead of passing in an array of byte, short or int I boxed them into
an array of objects them unboxed them within the called method. I don't
like this implementation as it is not all that elegant, but it will do
for now until I find a better approach.

Mark

Nicholas Paldino [.NET/C# MVP] wrote:
Mark,

The problem here is that arrays are not inherently polymorphic. So, as
a result, the compiler tries to match up the call with the appropriate
function, it sees that byte[] does not cast down to object[], but it does
cast down to object, and that's why the call is made.

You might want to try defining the parameter with the object array as
System.Array, and see if that works.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

<Lo*****@hotmai l.comwrote in message
news:11******** *************@b 28g2000cwb.goog legroups.com...
Hello all,

I recently ran into a strange behavior which I don't understand. I
have two 'Add' method which a slightly different signature which they
look like

public void Add( string varName, ScriptVarType type, object value )
public void Add( string varName, ScriptVarType type, object[] values
)

Then in another part of the source base I have the following
declaration

private void Extract( ... )
{
byte[] byteElements;

...

// Where all arguments are assigned before the call is made
ScriptVars.Add( groupsRegEx[1].Value, type, byteElements );
}

The strange item which I don't understand is that instead of call the
method that accepts an array of objects the code is calling the method
where the signature only accepts a single object. Can someone explain
why this is? My guess is since object is the base class of most items
it is also the base class for arrays. Any explanation will be
appreciated. For the time being I will just end up change the method
names to force call to the correct method istead of relying on the
compiler looking at the signature. Thanks

Mark
Aug 16 '06 #5

Marc Gravell wrote:
Two simply workarounds leap to mind:
// 1: since Array is the base of all array implementations
public void Add( string varName, ScriptVarType type, Array values) {}

// 2: (2.0 only) generics;
// note you generally won't have to specify T
// when calling - i.e. declare an int[] vals and call Add(blah, vals);
public void Add<T>( string varName, ScriptVarType type, T[] values) {}

Marc

Marc,

I think the first solution you have provided provides me with a nice
approach and it does appear to work well. I would use the second
approach, but as in my first implementation of using generics for this
project I had to scrap it as the variable is not known at compile time
and only as a script file is parsed, thus I always get "Cannot convert
type 'T[]' to 'byte[]' or other data types.

Is there a nice way of dealing with this?

So if I have my method signature that looks like

public void Add<T>( string varName, ScriptVarType type, T[] values )

then depending upon the type of variable that is determined at run-time
I need to cast it to a byte, short, int, float or string (etc..). I
could provide a signature for each variable type, but I was hoping to
have one method that accepts the arguments and cast them to the
appropriate type. I am not quite sure what the best approach is. I
was also having issues using bitwise operation (masking) of generics as
I would always get compiler errors. I really was hoping to use
generics, but I ran into problems using them when I had value and ref
types mixed.

Mark

Aug 16 '06 #6
then depending upon the type of variable that is determined at run-time
I need to cast it to a byte, short, int, float or string (etc..).
Generics is not the solution to every problem, however, if you can elaborate
on what you are trying to do (perhaps a little pseudocode as to why you need
to know the specific types), then I might be able to help. The framework
provides a number of handy interfaces (which framework objects supprt) and
helper classes to assist with generics, such as IEquatable<T>,
IComparable<T>, EqualityCompare r<T>.Default, etc.

Reflection is an option, but could be just as messy, and I don't like using
it if there is a perfectly good compile-time alternative available to me...
I was also having issues using bitwise operation (masking) of
generics as I would always get compiler errors.
What with things like ints, enums, etc? Yup, that's a right royal pain.
Can't be done neatly via generics AFAIK.
I ran into problems using them when I had value and ref
types mixed.
Anything specific? Note things like default(T), new(), and the : class / :
struct constraints may be of use. But again, generics is not a "fixes
everything ever" kind of thing. It helps though.

Marc
Aug 17 '06 #7

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

Similar topics

1
429
by: vishakha.ganjoo | last post by:
' C Sharp function - Start ' private void id_ok_Click(object sender, EventArgs e) '{ ' try ' { ' _job = new OsaScanJob((OsaSessionState)Session); ' _job.Create(); ' _job.Completed += new Osa.BusinessObjects.Job.OsaJobCompleteEventHandler(job_Completed);
2
1303
by: PinoyDotnet | last post by:
I am just starting 2.0, so I have this In ASPNET 1.X there is a method called InitializeComponent() which clearly wires in the Page_Load method to the Load event, like this: private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load);
10
3280
by: Jon | last post by:
I'm investiging multi-threaded GUI applications; specifically the technique used to ensure that controls are only modified under the correct thread. The standard technique is to use if(InvokeRequired == true) ... BeginInvoke(...) ... I have some code that ensures that an event fired from a worker (non-GUI) thread will use the appropriate BeginInvoke call for synchronisation. By offloading the synchronisation onto the worker thread the...
7
10238
by: Tim | last post by:
When there is a need to pass some dynamic information between 2 managed assemblies, the "Dictionary object" in Generic form can be used as a method parameter to pass the information. The information that needs to be passed can be stored as Key-Value pairs, and the method signature remains the same. That way, handling future requirements of passing additional details to the callee can be handled without changing the method signature. Is...
6
2346
by: TPJ | last post by:
Help me please, because I really don't get it. I think it's some stupid mistake I make, but I just can't find it. I have been thinking about it for three days so far and I still haven't found any solution. My code can be downloaded from here: http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some scripts for GNU/Linux system (bash to be precise). All you need to know is that there are four classes. (Of course, you may...
52
3231
by: Julie | last post by:
I'm supporting an application at work. Below are some code segments that I can't understand how they work. First let me say, I would never code this standard. I'm just really creeped out that it works. Here's the setup. I have a function, called GetEmployeeCertifications, that is going to make a call to a SQL DB and return a result set. This module calls another function, called FillParameters, to determine if SQL parameters need to...
3
2860
by: intrader | last post by:
What I have is a class A with a method Foo. I would like to create a thread that instances A and then calls Foo asynchronously while performing other duties. I think that the solution is to write an asynchronous version of Foo so that the caller can pass a callback as in the signature: public static IAsyncResult Foo( FooParams fooParams, AsyncCallback requestCallback,
3
1817
by: Dhananjay | last post by:
Hi All, I am facing problem when i am converting C#.net code(Delegate concept) into vb.net. I am unable to do that . Can someone help me to solve the problem. I am providing my C#.net code. ==================================my code is :- ====================================== static public List<MembershipUserWrapperGetMembers(bool
4
2232
by: =?Utf-8?B?dmlwZXJ4MTk2Nw==?= | last post by:
We are having an issue with an application we are developing. We have a Legacy COM DLL in C++ that we have converted to Visual Studio 2008. This COM DLL has methods that are calling Managed C# assemblies as pass thru to support legacy applications in an effort to move our code to the new Code base. Our COM Object can be instantiated on Windows XP in any COM supported environment using Visual C++, Visual Basic, ASP.NET or ASP and works...
0
9387
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
10148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
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...
0
8822
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
7368
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
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
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.