473,657 Members | 2,385 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing null as an "out" parameter

Hi there,

Is it possible to pass null to a function taking an "out" (or "ref")
parameter in C#. I'd like to do something like the following (which doesn't
compile of course). Thanks in advance.

int SomeValue;
Func(null, SomeValue); // Any way to pass null for either arg?

void Func(out int Param1, out int Param2)
{
if (Param1 != null)
{
Param1 = Whatever1();
}

if (Param2 != null)
{
Param2 = Whatever2();
}
}
Aug 23 '06 #1
7 14658
I don't think this is an out vs. ref issue...

Your code won't compile in C# 1.x because null is only an acceptable
value for reference types (ones based on a class, rather than anything
like int, float, or a struct). I'm not overly familiar with the C# 2.0
compiler, but I believe it'll let you have nullable value types if you
append ? to the type name. Does your code work if you use "int?"
rather than "int" ?

Eq.
Aug 23 '06 #2
Well, since you look at the values inside the method, you probably mean
"ref", in which case something like:
int? binMe = null, someValue = 0;
Func(ref binMe, ref someValue); // Any way to pass null for either arg?
Console.WriteLi ne(binMe);
Console.WriteLi ne(someValue);
static void Func(ref int? Param1, ref int? Param2) {
if (Param1 != null) Param1 = 7; // random
if (Param2 != null) Param2 = 5; // random
}

It *looks* like you are trying to decide which values to lookup (perhaps
from a DB); in which case, another option is some kind of bitmask, perhaps
in a [Flags] enum.
Aug 23 '06 #3
I don't think this is an out vs. ref issue...
>
Your code won't compile in C# 1.x because null is only an acceptable value
for reference types (ones based on a class, rather than anything like int,
float, or a struct). I'm not overly familiar with the C# 2.0 compiler, but
I believe it'll let you have nullable value types if you append ? to the
type name. Does your code work if you use "int?" rather than "int" ?
Thanks for the response. Perhaps it was a bad example then since the args
will be reference types in practice (I'm coming from the C++ world where no
such issues exist). If they are reference types then is this doable? Thanks
again.
Aug 23 '06 #4
"Marc Gravell" <ma**********@g mail.comwrote in message
news:ux******** ******@TK2MSFTN GP05.phx.gbl...
Well, since you look at the values inside the method, you probably mean
"ref", in which case something like:
int? binMe = null, someValue = 0;
Func(ref binMe, ref someValue); // Any way to pass null for either arg?
Console.WriteLi ne(binMe);
Console.WriteLi ne(someValue);
static void Func(ref int? Param1, ref int? Param2) {
if (Param1 != null) Param1 = 7; // random
if (Param2 != null) Param2 = 5; // random
}

It *looks* like you are trying to decide which values to lookup (perhaps
from a DB); in which case, another option is some kind of bitmask, perhaps
in a [Flags] enum.
Thanks for the response. I'm not sure what the "?" in "int?" does however
(haven't seen this before but will look it up). In any event, passing bit
flags is inconvenient :) In the general case, when one has a function that
returns multiple out arguments and a client is only interested in a subset
of them, the ability to simply pass "null" for the others is very convenient
(and saves you from having to declare variables unnecessarily).
Aug 23 '06 #5

John Layton wrote:
"Marc Gravell" <ma**********@g mail.comwrote in message
news:ux******** ******@TK2MSFTN GP05.phx.gbl...
Well, since you look at the values inside the method, you probably mean
"ref", in which case something like:
int? binMe = null, someValue = 0;
Func(ref binMe, ref someValue); // Any way to pass null for either arg?
Console.WriteLi ne(binMe);
Console.WriteLi ne(someValue);
static void Func(ref int? Param1, ref int? Param2) {
if (Param1 != null) Param1 = 7; // random
if (Param2 != null) Param2 = 5; // random
}

It *looks* like you are trying to decide which values to lookup (perhaps
from a DB); in which case, another option is some kind of bitmask, perhaps
in a [Flags] enum.

Thanks for the response. I'm not sure what the "?" in "int?" does however
(haven't seen this before but will look it up). In any event, passing bit
flags is inconvenient :) In the general case, when one has a function that
returns multiple out arguments and a client is only interested in a subset
of them, the ability to simply pass "null" for the others is very convenient
(and saves you from having to declare variables unnecessarily).
The short answer: no.

However, there is a way to use Marc's bit masks but not pollute your
client code. It involves writing a lot of overloads, and won't work if
several (or all) of your arguments are the same type, but what about
this:

[Flags]
private enum ReturnType = {
ReturnCustomer = 0x01,
ReturnSupplier = 0x02,
...
};

private void Fetch(ReturnTyp e whatToReturn, out Customer cust, out
Supplier supp)
{
if ((whatToReturn & ReturnType.Retu rnCustomer) != 0)
{
cust = ... ;
}
if ((whatToReturn & ReturnType.Retu rnSupplier) != 0)
{
supp = ... ;
}
}

public void Fetch(out Customer cust, out Supplier supp)
{
Fetch(ReturnTyp e.Customer | ReturnType.Supp lier, out cust, out
supp);
}

public void Fetch(out Customer cust)
{
Supplier dummySupplier;
Fetch(ReturnTyp e.Customer, out cust, out dummySupplier);
}

public void Fetch(out Supplier supp)
{
Customer dummyCustomer;
Fetch(ReturnTyp e.Supplier, out dummyCustomer, out supp);
}

As I said, it doesn't work for all scenarios, but it does hide the
declaration of unnecessary variables inside overloaded methods.

Aug 23 '06 #6
Thanks for the suggestion. It looks like I have little choice but it's a
pain IMO :) Anyway, thanks again.
Aug 23 '06 #7
"int?" is a C# shortcut for the 2.0 generic (immutable) struct
Nullable<int>; Nullable<T(in general) sports a struct T and a bool
(.HasValue) to indicate if it has a value or should be considered null. Note
that since it is a struct it never really *is* null (in the object sense),
but that the compiler infers null equality via the .HasValue property.

Note, however, that you could achieve a similar effect in 1.1 using "magic
numbers", such as int.MinValue to mean "ignore this".

To be honest, however, I'm not really loving this whole approach anyway - it
seems (more than) a bit unsightly; perhaps I'd go for something a whole lot
simpler (ignore names):

public class SomethingResult { // or struct, depending
public int SomeValue;
public float SomeOtherValue;
public bool SomethingElse;
}

[Flags]
pulic enum QueryOptions {
None = 0, SomeValue = 1, SomeOtherValue = 2, SomethingElse = 4, All = 7
}

public SomethingResult DoSomething(Que ryOptions options) {
SomethingResult result = new SomethingResult ();
if((options & QueryOptions.So meValue) == QueryOptions.So meValue)
result.SomeValu e = // do something
if((options & QueryOptions.So meOtherValue) == QueryOptions.So meOtherValue)
result.SomeOthe rValue= // do something
if((options & QueryOptions.So methingElse ) == QueryOptions.So methingElse)
result.Somethin gElse = // do something
}

You can now just call DoSomething() specifying what you want, and then
inspect the returned object to get the values (only looking at the ones you
asked for; the rest will default to null/0/false). No hastle with ref / out;
no setting up 20 dummy parameters just because you want to read one value;
very friendly, and compatible with both 1.1 and 2.0 runtimes.

Marc

Aug 24 '06 #8

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

Similar topics

1
1134
by: Jim | last post by:
I have a class with several public member variables which I pass to a library function as an "out" parameter. I noticed that when the function returned, all the data was "lost". Do classes used in this fashion need some kind of "clone" method much like the c++ copy constructor to move the data back to the calling method properly? Thanks, Jim
8
13173
by: Dave Veeneman | last post by:
Can I pass a method pass one of its out parameters to another method? C# is telling me I can't. Let's say I have two methods, FooManager and FooWorker. FooManager is part of a class that acts as a coordinator for several other classes. FooManager basically passes its parameters, including an output parameter 'x', on to FooWorker, a worker method in another class. FooWorker does the actual work and assigns to x. When FooWorker is done, it...
1
1803
by: mei xiao | last post by:
Hi, In my web service method (written in C#), I have a method like public string myMethod(out int test1, string test1) but when I use a web client to access this method, I got a run time exception: System.NullReferenceException: object reference not set to an instatnce to an object. What could be the problem and how to fix it? Thank you very much.
1
2270
by: Alex Chan | last post by:
Hi Group, I have written a window service wtih SAP.NET Connector which is to fulfil request from SAP client. SAP client will call a function exposed by my window service that has a big "out" parameter. That "out" parameter is of class SAPTable, you can regard that as DataTable. As everytime SAP client issue request to my window service, it will connect to oracle and do some searching and return the result in a SAPTable. I did a volume...
14
6138
by: Pollux | last post by:
I'm having a problem with something I thought was quite simple. I have a function in a C DLL. Let's call it SomeFunction. This is the prototype for SomeFunction: void SomeFunction(char * anArrayOfChars); where anArrayOfChars is an out parameter. I thought all I had to do was declare it as follows:
5
2225
by: web1110 | last post by:
This code public void ReturnArray(out string strArray) { string theArray=new string{"aaa", "bbb", "ccc"}; try { strArray=theArray; }
11
3422
by: dahuzizyd | last post by:
Hi all: I think I had a problem with using out parameter , why the instance of 'SubClass' can't convert to 'BaseClass' ? my code is : ---------------------------------------------- using System; namespace ConsoleApplication2 { class Class1
5
5096
by: Hendri Adriaens | last post by:
Hi, I want to write a method to read the first column from a textfile and output them in 2 arrays to the main program. I don't know the length of the column beforehand. I use out to avoid needing to assign the array a value, but still, I get the following complaint: Use of unassigned out parameter 'variabelen'. My code is below. I don't use it actually, I want to assign it a value. I hope you can help.
6
4536
kaleeswaran
by: kaleeswaran | last post by:
hi! i am new to myql procedure.. i can get the output value from the procdure if i use select option..but i could't get the value while i am using the out parameter.it shows null.. when i try to print the variable.. what is the pbm?.............. give me the solution... thank you, kalees
0
8420
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
8740
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
8516
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
8617
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...
1
6176
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
4173
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
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
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
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.