lock and overloads

A

am

Hy,
I need to do a sealed class with some functions that ruturns me a
string with a required length.

I.e.

public class MyClass
{
static Object lockStringFixedLength = new Object();

public static string GetStringFixedLength(
string stringToChange,
int length,
char charToUse,
bool insertAtLeft,
bool cutIfLonger
)
{
lock( lockStringFixedLengthString )
{
string fixedString = "";

if ( stringToChange.Length == length )
return stringToChange;

if ( stringToChange.Length < length )
{
string stringToAdd =
new string( charToUse, length - stringToChange.Length );

if ( insertAtLeft )
{
fixedString = stringToAdd + stringToChange;
}
else
{
fixedString = stringToChange + stringToAdd;
}
}
else
{
fixedString = ( cutIfLonger )
? stringToChange.Substring( 0, length )
: stringToChange;
}

return fixedString;
}
}


I need to add many overloads for default options.

I.e.

public static string GetStringFixedLength(
string stringToChange,
int length,
char charToUse
)
{
return GetStringFixedLength(
stringToChange,
length,
charToUse,
false,
true
);
}


public static string GetStringFixedLength(
string stringToChange,
int length
)
{
return GetStringFixedLength(
stringToChange,
length,
' ',
false,
true
);
}


Should I declare and create a static object for every overload to use
in a lock block, or can I do something else? I need many overloads
(more than 20, and I need to write many other functions with a lot of
overloads in the same class).

Some tips?

Thanks a lot.
 
M

Mattias Sjögren

Should I declare and create a static object for every overload to use
in a lock block, or can I do something else?

I don't see why you're using lock at all. You're not reading or
writing any shared state.



Mattias
 
A

am

You're right...
I shouldn't need lock in that case.
However I will in others. Have you some tips?
Thanks a lot!
 
I

Ignacio Machin \( .NET/ C# MVP \)

As Mattias said you are not sharing nothing, so there is no need to use a
lock

Also you are talking about a sealed class in your text , but in your code
you don't have a sealed class, you do have a "static" class.

What is what you want to do after all?


cheers,
 
A

am

In the class that I will build there will be many functions, not just
that I wrote in the exemple.

Some functions will share resources, so I have to avoid simultaneous
access.

The class should be sealed (I forgot it in the exemple), and I have to
build it with c# 1.1, "static class" is c# 2.0.
Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top