4

If I have a static method to convert one object to another object, is this method thread safe in C#?

public static AnotherDataClass Convert(MyDataClass target)
{
     AnotherDataClass val = new AnotherDataClass();
     // read infomration from target
     // put information into val;
     return val;
}

Just want to make the question more clear....

when invoke the convert method.... we can assume that target is not going be be modified. since the Convert method only interested in the "attrubite" of target

Engineert
  • 192
  • 1
  • 1
  • 16
jojo
  • 13,583
  • 35
  • 90
  • 123
  • 8
    Impossible to say, does *target* have any properties or fields that are writable by other threads? Then it is not thread-safe. – Hans Passant Dec 03 '11 at 20:25
  • I think you need to understand what "thread-safe" actually means first. – x0n Dec 03 '11 at 20:25
  • 2
    Your example is not a static method. – John Saunders Dec 03 '11 at 22:03
  • @JohnSaunders, why do you say the example is not a static method? – Fractal Aug 07 '19 at 20:23
  • @Fractal I'm only guessing from eight years ago, but that method depends on the contents of an instance. It could have been written as an instance method of the `MyDataClass` method. Hence, it's subject to the same thread safety issues as the corresponding instance method would have had. Consider what could happen if another thread were modifying `target` while it's being used. – John Saunders Aug 15 '19 at 02:12

1 Answers1

2

No, it is not.

"A method would be thread safe if it would b accessing data that won't be accessible to any other thread" If this definition is correct then the method is not thread safe

Reason

MyDataClass seems reference type to me so there is a chance that multiple threads might be changing the target variable

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122